gpt4 book ai didi

javascript - 如何解决从网页向 Chrome 扩展程序发送数据的问题?

转载 作者:行者123 更新时间:2023-11-30 09:23:52 41 4
gpt4 key购买 nike

我正在尝试将数据从我的网页传递到 chrome 扩展程序。

manifest.json(我尝试先在我的本地环境中执行此操作)

  "externally_connectable": {
"matches": ["*://localhost/*"]
}

在 listen.js(后台脚本)中:

chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
if (sender.url == blacklistedWebsite)
return; // don't allow this web page access
if (request.openUrlInEditor)
alert('test2');
alert(request.openUrlInEditor);
});

上面没有显示任何警报。

当我导航到 chrome://extensions/时,我通过查看 ID 获得了解压后的 chrome 扩展的扩展 ID。在我本地主机环境的网页中

// DEVELOPMENT extension ID
var editorExtensionId = "fppgjikaoolnlcmdjalbfkmlcadcckmb";

var url = 'test';
// Make a simple request:
chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url},
function(response) {
if (!response.success)
handleError(url);
});

当我运行它时。在浏览器中,我收到一条错误消息:

Error in event handler for (unknown): TypeError: Cannot read property 'success' of undefined

我不确定从哪里开始调试它。

最佳答案

在对您的代码进行一些更改后,我能够实现您的目标。

完整代码见下方。

manifest.json

{
"manifest_version": 2,
"name": "CS to Bg Communication",
"version": "0.1",
"background": {
"scripts": ["listen.js"]
},
"content_scripts": [
{
"all_frames" : true,
"matches": ["<all_urls>"],
"js": ["contentscript.js"]
}
],
"browser_action": {
"default_popup": "popup.html"
},
"externally_connectable": {
"matches": ["*://localhost/*"]
}
}

listen.js - the background script

chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
blacklistedWebsite = 'http : / / yourdomain . com /';
if (sender.url == blacklistedWebsite)
return; // don't allow this web page access
if (request.openUrlInEditor) {
alert('test2 - ' + request.openUrlInEditor);
sendResponse({"success": true, "AckFromBG": "I have received your messgae. Thanks!"}); // sending back the acknowlege to the webpage
}
});

contentscript.js - the content script - actually does nothing

console.log("this is content script");

web-page.html - The local web page

<html>
<body>

This page will will send some message to BG script

<script type="text/javascript">
// DEVELOPMENT extension ID
var editorExtensionId = "fjaedjckfjgifecmgonfmpaoemochghb"; // replace with your extension ID
var url = 'test';
chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url}, function(response) {
console.log(response);
if (!response.success)
handleError(url);
});
function handleError(url) {
console.log(url);
}
</script>
</body>
</html>

变更摘要:

  • 已定义 blacklistedWebsite - 这是未定义的。

  • 添加了sendResponse({"success": true, "AckFromBG": "我已经收到
    你的消息。谢谢!”});
    将确认发送回网页。

  • 定义 函数 handleError(url) {
    控制台日志(网址);
    这没有定义。

就是这样。希望这会解决您的问题。

关于javascript - 如何解决从网页向 Chrome 扩展程序发送数据的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49989246/

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