我正在尝试将消息从后台页面发送到内容脚本,然后将该内容脚本中的消息发送到注入的脚本.我试过这个,但它没有用.
这是我的代码的样子.
的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.runtime.onInstalled.addListener.
但是在更新扩展后,所有内容脚本都无法连接到后台页面.我们得到一个错误:Error connecting to extension ....
可以使用chrome.tabs.executeScript... 重新注入内容脚本但是如果我们有一个敏感数据应该在更新之前保存并在更新后使用怎么办?我们能做什么?
此外,如果我们重新注入所有内容脚本,我们应该正确地拆除以前的内容脚本.
在不丢失用户数据的情况下,从内容脚本处理扩展更新的正确方法是什么?