IT Man
IT Man

Reputation: 1036

Use onClick in chrome extension

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?

Upvotes: 1

Views: 1699

Answers (1)

Haibara Ai
Haibara Ai

Reputation: 10897

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();
    

Upvotes: 4

Related Questions