简体   繁体   中英

Chrome Extension - js with parameters not working

I've been coding chrome extension popup with js that calls with a parameter.

here is html file

<!DOCTYPE html>
<html>
<head></head>
<body>
 <p id="demo">=a</p>
    <button type="button" id="do-count1">Count1</button>
    <button type="button" id="do-count2">Count2</button>  
  <script src="popup.js"></script>
</body>
</html>

since chrome extension js must be separated

popup.js

var a=0;
 function count(k) {
     a = a + k;
     document.getElementById('demo').textContent = a;
}
document.getElementById('do-count1').onclick = count(2);
document.getElementById('do-count2').onclick = count(5);

when opening the popup window it gives 7, as those 2 functions executed automatically without clicking. further the buttons don't work.

a similar question was asked The Chrome extension popup is not working, click events are not handled

but my question one step advanced since i need to call js function with a parameter onclick.

Currently you're assigning a result of the function call , not a function reference.

Your options are:

  • use bind() to create a function wrapper that will pass the parameter:

     element1.onclick = count.bind(null, 2); element2.onclick = count.bind(null, 5); 

    Note: this of the onclick function will be lost this way.

  • or use a simple function wrapper:

     element1.onclick = function() { count(2) }; element2.onclick = function() { count(5) }; 

    Note: this of the onclick function will be lost this way, to preserve it:

     element1.onclick = function() { count.call(this, 2) }; element2.onclick = function() { count.call(this, 5) }; 
  • use an HTML attribute:

    popup.html:

     <button type="button" id="do-count1" data-add="2">Count1</button> <button type="button" id="do-count2" data-add="5">Count2</button> 

    popup.js:

     function count() { document.getElementById('demo').textContent = a = a + this.dataset.add; } element1.onclick = count; element2.onclick = count; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM