Javascript 将数据从页面发送到chrome扩展
我试图将一些数据从web应用程序发送到chrome扩展(如中所述),但出现错误:Javascript 将数据从页面发送到chrome扩展,javascript,google-chrome,google-chrome-extension,Javascript,Google Chrome,Google Chrome Extension,我试图将一些数据从web应用程序发送到chrome扩展(如中所述),但出现错误:Unchecked runtime.lastError:无法建立连接。接收端不存在。 我的内容脚本: chrome.runtime.onMessageExternal.addListener( function(request, sender, sendResponse) { if (sender.url == blocklistedWebsite) return; // don't all
Unchecked runtime.lastError:无法建立连接。接收端不存在。
我的内容脚本:
chrome.runtime.onMessageExternal.addListener(
function(request, sender, sendResponse) {
if (sender.url == blocklistedWebsite)
return; // don't allow this web page access
if (request.openUrlInEditor)
openUrl(request.openUrlInEditor);
});
这是我的舱单:
{
"name": "test-extension",
"version": "0.0.1",
"manifest_version": 2,
"background": {
"scripts": ["src/bg/background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["http://localhost/*"],
"js": ["src/inject/inject.js"]
}
],
"externally_connectable": {
"ids": ["abcdefghijklmnoabcdefhijklmnoabc"],
"matches": ["http://localhost/*"],
"accepts_tls_channel_id": false
}
}
和测试页面,我尝试在其中发送数据:
<body>
<button onclick="processData()">Send data to extension</button>
</body>
<script>
function processData() {
/* ... */
// The ID of the extension we want to talk to.
var editorExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";
// Make a simple request:
chrome.runtime.sendMessage(
editorExtensionId,
{ openUrlInEditor: 'https://google.com' },
function(response) {
if (!response.success) handleError(url);
}
);
}
</script>
向分机发送数据
函数processData(){
/* ... */
//我们要与之交谈的分机的ID。
var editorExtensionId=“abcdefghijklmnoabcdefhijklmnobc”;
//提出一个简单的请求:
chrome.runtime.sendMessage(
editorExtensionId,
{openUrlInEditor:'https://google.com' },
功能(响应){
if(!response.success)handleError(url);
}
);
}
这将向与您指定的URL模式匹配的任何页面公开消息传递API。URL模式必须至少包含第二级域,即禁止使用诸如“.com”、“co.uk”和“.appspot.com”之类的主机名模式。在网页中,使用runtime.sendmages或runtime.connect API向特定应用程序或扩展发送消息
参考:
可能是因为您的*问题出现在外部可连接的配置中。它不适用于
localhost
。为了在localhost
上使用它,我在我的主机文件中添加了以下几行:
127.0.0.1 my.localhost
然后将清单更改为:
"externally_connectable": {
"ids": ["*"],
"matches": [
"http://my.localhost/*",
]
您可能可以在
主机
文件中添加一个指向127.0.0.1的虚拟域,然后在可连接的文件中使用该域名。如果您需要更多详细信息,请尝试搜索现有答案。@wOxxOm它不起作用,我尝试了很多组合,“它”是一个模糊的描述。以下是我的意思,你可以找更详细的。@wOxxOm-thx!现在它开始工作了!