Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 251
pizzamiasucks Avatar asked Sep 18 '25 09:09

pizzamiasucks


1 Answers

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.

like image 168
yonran Avatar answered Sep 23 '25 13:09

yonran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!