2

I have the follwing code in the content.js of Google Chrome extension:

jQuery(document).ready(function () {
    jQuery("body").html('<input type="button" id="soso" value="asd" onclick="goFrame()" />');
});
function goFrame() {
    alert('Value');
}

The button is created successfully, but when I click on it the message doesn't appear and I got the follwing error in the Google Chrome console:

Uncaught ReferenceError: goFrame is not defined

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • The button your creatings onclick is pointing to goFrame that is in the context of the page. Where as your goFrame function in your code is in the context of the content script because thats where it was declared. After `JQuery("body")...` add the line `document.querySelector('#sos').onclick=goFrame;` – PAEz Jul 28 '12 at 19:09
  • @PAEz It's easy to learn jQuery ;) To bind a click event, use `.click()` - http://api.jquery.com/click/ – Rob W Jul 28 '12 at 20:42
  • @Rob W I have a SHOCKING memory and so like to stick to just JS, especially since I only do Chrome and so have all this nice new stuff....keeps things simple for me :) – PAEz Jul 28 '12 at 20:56

1 Answers1

4

First read Chrome extension code vs Content scripts vs Injected scripts.

To solve the problem, get rid off the inline event listener, and bind the event dynamically:

    ...
    var $input = $('<input type="button" id="soso" value="asd">').click(goFrame);
    jQuery("body").html($input);
});
function goFrame() {
    alert('Value');
}
Community
  • 1
  • 1
Rob W
  • 341,306
  • 83
  • 791
  • 678