Search code examples
javascriptgoogle-chrome-extensiondom-events

Chrome Extension - Event Listener for Appended Code


I am writing a Chrome extension where I am trying to create a GUI on top of an existing page. This GUI consists of an input text field, and a reply button. I have created the GUI by creating an HTML string, and appending it to the website.

I want to add an event listener so that when the reply button is pressed, it will trigger a function so I can send the data in the input text field to my server. From my understanding, once code has been appended to the page, it no longer has access to script.js therefore it cannot access an event listener. Is there an alternative?

Image of my GUI: http://www.filedump.net/index.php?pic=eventlistenermoot1328028688.jpg


Solution

  • The page you are injecting code into is sandboxed from content scripts. However your content scripts have full access to the page DOM, including events. That means that you can add an event listener to elements that you append. You have to add them unobtrusively so that the content script can then send a message to the background page:

    Content Script:

    var html = document.createElement('div');
        html.innerHTML = '<input id="clickMe" type="button" value="Click Me" />';
    document.body.appendChild(html);
    
    document.getElementById('clickMe').addEventListener('click', function() {
        // do stuff
    });