【发布时间】:2020-09-12 23:15:21
【问题描述】:
三天前我开始使用 chrome 扩展,我非常喜欢它。我遇到了一个问题:我最小化了重现我的问题的脚本:
如果我在 stackoverflow.com 上,我可以单击该图标,如果它向后台脚本发送消息并收到消息“工作”,则会打开一个弹出窗口,显示“工作”。
如果我现在重新启动浏览器,我会得到一个弹出窗口,开发者模式下的扩展可能有害,以及我是否要停用它们。我关闭了此消息,当我现在单击扩展程序时它不起作用并且我收到以下错误:
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
我发现后台脚本没有正在运行(我没有收到来自 background.js 的警报或打印到 background.js 控制台)。我想扩展程序和 background.js 可能被 chrome 阻止了,因为它是开发人员模式下的扩展程序。让扩展再次运行的唯一方法是从 chrome://extensions 刷新扩展。
我尝试使用持久性和非持久性后台脚本,但这并没有改变行为。
我的分析是否正确,因此是在网上商店部署脚本以使其正常运行的唯一解决方案?或者还有其他方法可以让开发者模式的应用在chrome启动时启动?
这是最简单的例子:
manifest.json
{
"name": "BackgroundScript Error",
"version": "0.0.1",
"manifest_version": 2,
"description": "When starting Chrome, background doesn't start, but when refreshing, background starts",
"page_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["declarativeContent", "<all_urls>"],
"background": {
"scripts": ["background.js"],
"persistent": false
}
}
background.js
chrome.runtime.onInstalled.addListener(function() {
console.log('Background script is running');
alert("Background is running");
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [new chrome.declarativeContent.PageStateMatcher({
pageUrl: {hostEquals: 'stackoverflow.com'},
})],
actions: [new chrome.declarativeContent.ShowPageAction()]
}]);
});
console.log('setting up connection to popup');
chrome.runtime.onConnect.addListener(connected);
});
chrome.runtime.onMessage.addListener(function(request, sender) {
console.log(request.action);
});
function connected(p) {
console.log("connected to "+p);
p.postMessage({action: 'didSomething', result: 'worked' });
p.onDisconnect.addListener(disconnected);
}
function disconnected(p) {
console.log("disconnected from "+p);
}
popup.js
var myPort
function onWindowLoad() {
var message = document.getElementById('message');
myPort = chrome.runtime.connect({name:"port-from-cs"});
myPort.postMessage({request: "doSomething"});
myPort.onMessage.addListener(function(m) {
console.log("In popup script, received message from background script: ");
message.innerHTML = m.result;
});
}
window.onload = onWindowLoad;
popup.html
<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js' ></script>
</head>
<body>
<div id="message">Popup</div>
</body>
</html>
谢谢!
【问题讨论】:
标签: javascript html google-chrome google-chrome-extension