1

I have a chrome extension with content_scripts. When page loads i'm appending new element to DOM using jquery:

urlTarget.parent().prepend("<div class='scout status' onClick='test()' data-domain='" + domainKey + "'></div>");

This works fine. I also defined a function inside my inject.js content script:

function test() {
    alert("this is test");
    return false;
}

After clicking appended element i get following error:

Uncaught ReferenceError: test is not defined

I've been reading about security restrictions in chrome extension framework (see docs), but i'm not sure if they are applied to content script also (documentation shows popup example), or am i am missing something else?

Kaz
  • 1,047
  • 8
  • 18
IT Man
  • 933
  • 3
  • 12
  • 33

1 Answers1

4

When you append the new element to DOM and register event listeners via onClick=XXX, in fact the browser expects that XXX is from page script. However, you know content scripts are isolated, they can't directly access variables/functions created by the page, and vice versa.

So here comes two workarounds:

  1. Add an id for the inserted element, and bind event listener in the content script via the following way

    // Assuming the id is ID
    document.getElementById('ID').addEventListener('click', test);
    
  2. Append a script tag into the page (Use a content script to access the page context variables and functions)

    var actualCode = `
      function test() {
        alert("this is test");
        return false;
      }
    `;
    
    var script = document.createElement('script');
    script.textContent = actualCode;
    (document.head||document.documentElement).appendChild(script);
    script.remove();
    
Phil Dukhov
  • 67,741
  • 15
  • 184
  • 220
Haibara Ai
  • 10,703
  • 2
  • 31
  • 47
  • Thanks that explains script behavior. Actually my purpose is to dynamically call a function from inside of inject script. By dynamically i mean when handling click on appended element that contains data attribute value with name of the function to be called, i will be able to call this function "from string". Instead of `onClick` i have also tried `eval()` - but, effect is the same. – IT Man Sep 21 '16 at 05:27