猿问

Chrome扩展程序:后台脚本未启动,仅在刷新后

三天前,我开始使用chrome扩展程序,我非常喜欢它。我遇到了一个问题:我最小化了重现我的问题的脚本:


如果我 stackoverflow.com,我可以单击该图标,如果它向后台脚本发送消息并收到消息“工作”,则会打开一个弹出窗口,上面写着“工作”。


如果我现在重新启动浏览器,我会得到一个弹出窗口,说明开发人员模式下的扩展可能是有害的,以及我是否要停用它们。我关闭此消息,当我现在单击扩展名时,它不起作用,我收到以下错误:


Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

我发现后台脚本没有运行(我没有收到来自后台的警报.js或打印到后台.js控制台)。我想扩展程序以及背景.js可能被chrome阻止启动,因为它是开发人员模式下的扩展程序。使扩展再次运行的唯一方法是从 chrome://extensions 刷新扩展。


我尝试使用持久和非持久背景脚本,但这并没有改变行为。


我的分析是否正确,因此是否是在 Webstore 上部署脚本以使其正常运行的唯一解决方案?或者,是否有其他方法可以在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

    }

}

背景.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);

}



互换的青春
浏览 775回答 2
2回答

侃侃尔雅

不,您无需部署到网上商店即可使其正常工作。你遇到了一个问题,因为你已将大部分后台脚本活动附加到侦听器 - 仅当安装扩展或清单版本更改时才会触发侦听器。第二次重新启动浏览器时,您的扩展已安装,清单版本保持不变,因此不会触发该事件。chrome.runtime.onInstalled

白衣非少年

我想出了该怎么做:如前所述,已安装侦听器中的函数仅在实际安装脚本时调用(例如刷新),而不是在重新启动浏览器时调用。我发现了我的新手错误:我异步注册了听众,因为在Chrome文档中被列为“不该做”。详细来说,这条线应该从已安装的监听器中取出:chrome.runtime.onConnect.addListener(connected);感谢您为我指出正确的方向!
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答