gpt4 book ai didi

javascript - 调用网页内 'content_script.js'中的函数

转载 作者:行者123 更新时间:2023-11-28 15:39:36 30 4
gpt4 key购买 nike

我正在开发一个扩展程序,希望使其与我的网站进行交互。但是当我尝试调用位于“content_script.js”文件中的函数时,它说该函数未定义!

最佳答案

第 1 步:了解 isolated context内容脚本在其中运行。

Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page. It looks to each content script as if there is no other JavaScript executing on the page it is running on. The same is true in reverse: JavaScript running on the page cannot call any functions or access any variables defined by content scripts.

第 2 步:由于您正在与自己的网站进行交互,因此首选方法是使用 messaging and externally_connectable property .

您需要在 list 文件中声明您的扩展程序可从您的站点进行外部连接:

"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");
}
);

注意:只有安装了扩展程序/可外部连接时,此函数才会暴露给页面。

最后,在您的内容脚本中,对该消息使用react:

chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
if (request.ping) {
console.log("Ping received from the page");
sendResponse({pong: true});
}
}
);

一般来说,请阅读 Messaging了解更多信息。

关于javascript - 调用网页内 'content_script.js'中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24236255/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com