Afshin Mehrabani
Afshin Mehrabani

Reputation: 34919

Call an external function from content script

Suppose I have boo function inside an external JavaScript file, from domain http://localhost/file.js:

file.js:

function boo() {
  return 1;
}

How can I call the boo function from content script in chrome extension?

Upvotes: 1

Views: 1632

Answers (2)

Reyraa
Reyraa

Reputation: 4274

According to this doc from Mozilla:

Content scripts can access the DOM of a page, of course, just like any scripts that the page has loaded (page scripts). But content scripts are insulated from page scripts:

  • content scripts don't see any JavaScript objects added to the page by page scripts
  • if a page script has redefined the behavior of some DOM object, the content script sees the original behavior.

Reasons:

  1. it means that content scripts don't leak objects to web pages, potentially opening up security holes.

  2. it means that content scripts can create objects without worrying about whether they might clash with objects added by page scripts.

Update

@Xan was right! thanks Xan. if you need to interact with a function added by other page script, messaging between content script of your add-on and the page script is like this:

// main.js

var tabs = require("sdk/tabs");
var mod = require("sdk/page-mod");
var self = require("sdk/self");

var pageUrl = self.data.url("page.html")

var pageMod = mod.PageMod({
  include: pageUrl,
  contentScript: "console.log(unsafeWindow.foo);"
})

tabs.open(pageUrl);

where foo is a variable added by a page script.

Upvotes: 1

MeLight
MeLight

Reputation: 5555

You'll need to run a content script that creates and injects a <script> element that calls the page's boo() function.

Your content script should have something alone the lines of:

function runBoo() {
    var myBoo = document.createElement('script');
    myBoo.id = 'myBoo';  //helpful for removing the element later, not required to work
    myBoo.innerText = 'boo();'
    document.body.appendChild(myBoo); //if you plan on calling boo() multiple times, don't forget to delete the previously added myBoo elements
}

window.onload = function() {
//call runBoo() from content whenever you want to run the page's boo() function
   runBoo();
}

Upvotes: 3

Related Questions