0

What could be the reason why script only run once for a Chrome extension? Here is our code:

inject.js

var s = document.createElement('script');
// TODO: add "script.js" to web_accessible_resources in manifest.json
s.src = chrome.extension.getURL('script.js');
s.onload = function() {
    this.remove();
};
(document.head || document.documentElement).appendChild(s);

$( document ).ready(function() {
    console.log("start")
    //$("body").bind("DOMSubtreeModified", function() {
        $("#btn").click(function(){
            console.log("do something")
        });
    //});
});

The expected behavior is for the click event to be fired everytime the #btn is clicked, however it only works once the page reloads and the succeeding clicks does not trigger what could be the bug here?

The click event will trigger every time if we bind to the DOMSubtreeModified however there are side effects, since our actual code calls for ajax resource, having the bind to DOMSubtreeModified fires the ajax request continuously as the page DOM changes.

quarks
  • 29,080
  • 65
  • 239
  • 450
  • This is for a Chrome extension, the code works fine if not deployed as a chrome extension, e.g. using JSfiddle – quarks Sep 14 '16 at 18:26
  • Actually you have a point, the problem I am trying to solve is why the click function only works once and next time the button is clicked it does not work, it should have been bound right? Just like the commented code there which is bind to DOMSubtreeModified which works – quarks Sep 14 '16 at 18:32
  • 2
    Well, it's because the element is dynamically recreated. I can't say for sure without seeing the page. Anyway, the simplest solution is probably `$(document).on('click', '#btn', function() {...});` – wOxxOm Sep 14 '16 at 18:32
  • I actually fixed it just now using the same code you have. Thanks! – quarks Sep 14 '16 at 18:53

0 Answers0