Function not defined creating a Chrome Extension Content Script

前提是你 提交于 2020-01-14 14:12:10

问题


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!


回答1:


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.




回答2:


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"]
  }]
}


来源:https://stackoverflow.com/questions/5162520/function-not-defined-creating-a-chrome-extension-content-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!