当前位置: 动力学知识库 > 问答 > 编程问答 >

Chrome plugin running a function but not found

问题描述:

I want my plugin to inject so that when i click on the button, it runs a function in the current tab. However, it's giving me a function not found error.. is there some way to do this?

This is my popup.html:

<script>

function start() {

chrome.tabs.executeScript( null,

{ code: "func_in_body()",

allFrames: true }

);

}

start();

</script>

and even though the function is in the page, it gives me an error

The error is:

Uncaught ReferenceError: func_in_body is not defined

(anonymous function)

though one of the buttons' onclick uses it. I'm not sure if there's a scope issue or not.

网友答案:

You don't need a popup to execute a function or a script on the current tab. What I did is, I made a background page with:

<html>
<head>
<script>
var iconName = "icon.png";
chrome.browserAction.setIcon({path:iconName});


  function onClicked(){
      chrome.tabs.executeScript(null, {file: "content_script.js"});
  }



  chrome.browserAction.onClicked.addListener(onClicked);
</script>
</head>
</html>

the background page has to be defined in the manifest.json

...
"background_page": "background.html",
...

and the last thing just create the content_script.js (or whatever you called it) and enter your code there.

Edit: Don't forget to add the permissions that your script can be executed on every site

...
"permissions": [
        "tabs",
        "http://*/*",
        "https://*/*"
    ],
...
网友答案:

JavaScript you inject into tabs is executed in a isolated environment and does not have access to the pages JavaScript. You can read more about it in the documentation.

分享给朋友:
您可能感兴趣的文章:
随机阅读: