我正在尝试将消息从后台页面发送到内容脚本,然后将该内容脚本中的消息发送到注入的脚本.我试过这个,但它没有用.
这是我的代码的样子.
的manifest.json
{
"manifest_version": 2,
"name": "NAME",
"description": ":D",
"version": "0.0",
"permissions": [
"tabs","<all_urls>"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content_script.js"]
}
],
"web_accessible_resources": [
"injected.js"
],
"background":{
"scripts":["background.js"]
}
}
Run Code Online (Sandbox Code Playgroud)
background.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response){});
});
Run Code Online (Sandbox Code Playgroud)
content_script.js
var s = document.createElement('script');
s.src = chrome.extension.getURL('injected.js');
s.onload = function(){
this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
document.dispatchEvent(new CustomEvent('Buffer2Remote', {todo: "LOL"}));
});
Run Code Online (Sandbox Code Playgroud)
injected.js
document.addEventListener('Buffer2Remote', function(e){
alert(e.todo);
});
Run Code Online (Sandbox Code Playgroud)
消息发送在第一部分background - > content_script中不起作用.我的代码有什么问题吗?
我正在尝试创建一个非常简单的 Chrome 扩展程序,它允许我突出显示网页上的一个词,右键单击以打开上下文菜单,然后通过简单地将该词附加到搜索 URL,在名为 Whitaker's Words 的数据库中搜索它. 我继续收到
“未检查的 runtime.lastError:无法建立连接。接收端不存在。”
每次运行代码并尝试使用上下文菜单时都会出错。
目前,我已经采取措施禁用所有其他扩展程序,并尝试使用 Chrome Messaging Docs 上的端口文档,但我无法通过这种方式解决问题。
背景.js
chrome.contextMenus.create({
title: "Search Whitaker's Words",
contexts: ["selection"]
});
chrome.contextMenus.onClicked.addListener(function() {
chrome.runtime.sendMessage({ method: "getSelection" }, function (response) {
sendToWW(response.data);
});
});
function sendToWW(selectedText) {
var serviceCall = 'http://archives.nd.edu/cgi-bin/wordz.pl?keyword=' + selectedText;
chrome.tabs.create({ url: serviceCall });
}
Run Code Online (Sandbox Code Playgroud)
在这里,我创建了一个上下文菜单,当单击菜单项时,我向上下文脚本发送一条消息,要求突出显示的选择。然后我将其返回给 background.js 中的另一个函数,该函数将使用搜索查询创建一个新选项卡。
内容.js
chrome.runtime.onMessage.addListener(function (message) {
if (message.method === "getSelection"){
var word = window.getSelection().toString().trim();
console.log(word);
chrome.runtime.sendMessage({ data: word });
}
else
chrome.runtime.sendMessage({}); // snub them.
});
Run Code Online (Sandbox Code Playgroud)
我在这里收听消息,然后从窗口中进行选择、修剪并将其发回。
清单文件 …
我有一个存储在chrome存储中的对象,如下所示:
{
"planA":
{
123: {key: 'some key'}
124: {key: 'some other key'}
},
"planB":
{
223: {key: 'some key'}
234: {key: 'some other key'}
}
}
Run Code Online (Sandbox Code Playgroud)
我想做点什么 chrome.storage.sync.remove([{"planA": "123"}]);
但这似乎不起作用 Error in response to storage.get: Error: Invalid value for argument 1. Value does not match any valid type choices.
来自文档 StorageArea.remove(string or array of string keys, function callback)
蚂蚁想法?
javascript storage google-chrome-extension google-chrome-storage