2

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.

Timmy
  • 12,468
  • 20
  • 77
  • 107

2 Answers2

2

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.

abraham
  • 46,583
  • 10
  • 100
  • 152
1

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://*/*"
    ],
...
Dominic
  • 3,353
  • 36
  • 47