pizzamiasucks
pizzamiasucks

Reputation: 41

Function not defined creating a Chrome Extension Content Script

I'm writing a Chrome content script and when I inject this in the DOM:

"<a href='#' onclick='alert(\"Hi!\");return false;'>Hi</a>"

it works fine (the alert pops up when I click it), however if I create a function for the alert, it will say function undefined. Ex:

"<a href='#' onclick='alertPlease(\"Hi!\");return false;'>Hi</a>"

function alertPlease(x){
     alert(x);
}

All my code is the same content script js file.

Do I have to place whatever code that can be used after loading in another js file in the background? I tried adding a background page with the 'alertPlease();' function, but that didn't work either.

Any hint will be greatly appreciated!
Thanks!

Upvotes: 4

Views: 3655

Answers (3)

KellyCode
KellyCode

Reputation: 787

Doing one of these today with manifest version 3, I learned:

I can't append a button to the page and use

<button type="button" onclick="myContentScriptFunction();">Call CS Function</div>

But, in the content script, I can do vanilla

let loadButton = document.createElement('button');
loadButton.innerText = 'Call CS Function';
loadButton.addEventListener('click', myContentScriptFunction);
document.querySelector('body').append(loadButton);

or jQuery

let loadButton = $("<button type="button">Call CS Function</button>")
loadButton.on("click", myContentScriptFunction)
$("body").append(loadButton);

And both worked as expected with all code in the content script

Info Source: Chrome Extension Samples Example

Upvotes: 0

yonran
yonran

Reputation: 19134

Content scripts run in an "isolated world." The webpage and content scripts can't see each other's JavaScript variables (although they can see the same DOM). When you add an onclick attribute within the DOM, the handler is created on the webpage's world, not your extension's world, so that code can't access the other function you defined. Instead of using an onclick handler, you should define your event listener in pure Javascript and then use addEventListener to attach it.

Isolated worlds are a feature to improve security and stability. Things are similar if you're developing within the Greasemonkey sandbox in Firefox.

Upvotes: 10

Nic Aitch
Nic Aitch

Reputation: 628

Specify any scripts in the manifest.json file under "content_scripts"

{
  "name": "My Extension",
  "content_scripts": [{
    "matches": ["<all_urls>"],
    "css": ["style.css"],
    "js": ["jquery-1.5.js", "script.js"]
  }]
}

Upvotes: -1

Related Questions