Reputation: 34919
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
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:
Reasons:
it means that content scripts don't leak objects to web pages, potentially opening up security holes.
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
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