我正在开发一个扩展程序,并想让它与我的网站互动。但是,当我尝试调用位于' content_script.js'文件说它没有定义函数!
答案 0 :(得分:4)
第1步:阅读内容脚本运作的isolated context。
内容脚本在称为孤立世界的特殊环境中执行。他们可以访问注入页面的DOM,但不能访问页面创建的任何JavaScript变量或函数。它将每个内容脚本视为在其运行的页面上没有执行其他JavaScript。反过来也是如此:页面上运行的JavaScript无法调用任何函数或访问内容脚本定义的任何变量。
第2步:由于您与自己的网站互动,首选方法是使用messaging and externally_connectable
property。
您需要在清单文件中声明您的扩展程序可从您的网站外部连接:
"externally_connectable": {
"matches": ["*://*.example.com/*"]
}
在网页代码中,您需要通过ID标识消息:
// The ID of the extension we want to talk to.
var myExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";
// Make a simple request:
console.log("Sending ping from the page");
chrome.runtime.sendMessage(myExtensionId, {ping: true},
function(response) {
if(response.pong) console.log("Pong received from content script");
}
);
注意:如果扩展程序已安装/可外部连接,则此功能仅向页面公开。
最后,在您的内容脚本中,对该消息作出反应:
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
if (request.ping) {
console.log("Ping received from the page");
sendResponse({pong: true});
}
}
);
一般情况下,请阅读Messaging了解详情。