Google chrome 从内容脚本调用外部函数
假设我在一个外部JavaScript文件中有Google chrome 从内容脚本调用外部函数,google-chrome,google-chrome-extension,Google Chrome,Google Chrome Extension,假设我在一个外部JavaScript文件中有boo函数,来自域http://localhost/file.js: file.js: function boo() { return 1; } 如何从chrome extension中的内容脚本调用boo函数?您需要运行一个内容脚本,该脚本创建并注入一个元素,该元素调用页面的boo()函数 您的内容脚本应该包含以下内容: function runBoo() { var myBoo = document.createElement('sc
boo
函数,来自域http://localhost/file.js
:
file.js:
function boo() {
return 1;
}
如何从chrome extension中的内容脚本调用
boo
函数?您需要运行一个内容脚本,该脚本创建并注入一个
元素,该元素调用页面的boo()
函数
您的内容脚本应该包含以下内容:
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();
}
您需要运行一个内容脚本,创建并注入一个调用页面的
boo()
函数的
元素
您的内容脚本应该包含以下内容:
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();
}
根据Mozilla的说法:
当然,内容脚本可以像其他脚本一样访问页面的DOM
页面已加载的脚本(页面脚本)。但是内容脚本
与页面脚本隔离:
- 内容脚本看不到任何由添加到页面的JavaScript对象 页面脚本
- 如果页面脚本重新定义了某个DOM对象的行为,则 内容脚本可以看到原始行为
// 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);
其中,foo是一个由页面脚本添加的变量。根据Mozilla的说明:
当然,内容脚本可以像其他脚本一样访问页面的DOM
页面已加载的脚本(页面脚本)。但是内容脚本
与页面脚本隔离:
- 内容脚本看不到任何由添加到页面的JavaScript对象 页面脚本
- 如果页面脚本重新定义了某个DOM对象的行为,则 内容脚本可以看到原始行为
// 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);
其中foo是一个由页面脚本添加的变量。然而,它是。内容脚本在设计上生活在一个孤立的世界中,这是正确的,但由于它们可以访问DOM,因此它们可以通过
标记注入代码。即使您引用的文档也会说:“通常,内容脚本和页面脚本之间的隔离是您想要的。但有时您可能希望与页面脚本交互:您可能希望在内容脚本和页面脚本之间共享对象,或者在它们之间发送消息。如果需要这样做,请阅读有关与页面脚本交互的内容。“我建议你仔细阅读另一个答案。我不再赘言。unsafeWindow
是特定于Firefox的。问题是特定于Chrome的。然而,它是。内容脚本在设计上生活在一个孤立的世界中,这是真的,但因为它们可以访问DOM,所以它们可以通过
标记注入代码。甚至你引用的文档都说:“通常,内容脚本和页面脚本之间的隔离是您想要的。但有时您可能希望与页面脚本交互:您可能希望在内容脚本和页面脚本之间共享对象,或者在它们之间发送消息。如果您需要这样做,请阅读有关与页面脚本交互的内容。“我建议您更仔细地阅读另一个答案。我不想进一步争辩。unsafeWindow
是特定于Firefox的。问题是特定于Chrome的。