为什么我的Google扩展似乎只有在我'我正在观察后台脚本控制台

Why does it seem that my Google Extension begins execution only when I'm observing background script console

本文关键字:观察 后台 控制台 脚本 我的 扩展 为什么 Google      更新时间:2023-09-26

我希望我的Google扩展在打开Google Chrome窗口后立即开始执行。我的后台.js中有以下代码:

if (window.Notification) {
    setInterval( function() { callAutomate(); }, 60000 );
}
function callAutomate() {
 // Code to automate hello-hello.com
}

清单文件如下-

{
    "name" : "Hello.co Extension",
    "version" : "1.1",
    "description" : "Say Hello",
    "background" :
    {
        "scripts": ["background.js"],
        "persistent": false
    },
    "page_action" :
    {
        "default_icon" : "hello-19.png",
        "default_title": "Hello World",
        "default_popup": "popup.html"
    },
    "content_scripts": [
        {
        "matches": ["https://www.hellohello.com/*"],    
        "js": [
            "content.js",
            "webDB.js"
            ]
        }
    ],
    "permissions": [ 
        "tabs",
        "storage",
        "unlimitedStorage",
        "webNavigation",
        "notifications",
        "https://www.hellohello.com/"
    ],
    "options_page": "options.html",
    "icons" : {
        "48" : "hello-48.png",
        "128" : "hello-128.png"
    },
    "manifest_version": 2,
    "web_accessible_resources": [
        "hello-48.png"
    ]
}

这是我的问题callAutomate();函数似乎只在我观察background.js的控制台日志时调用。然而,扩展的预期行为是调用callAutomate();从打开Google Chrome窗口开始,每隔一分钟就可以执行一次功能。

如有任何关于解释性代码的帮助,我们将不胜感激。

正如Chrome扩展文档中所解释的,有两种类型的背景页面:

  • 持久背景页:始终"打开"
  • 事件后台页面:根据需要"打开和关闭"

您正在使用第二个,如manifest.json文件中的"persistent": false所指定的,因此,当您正常加载页面时,后台代码不会自行执行
我非常确信,当您在后台页面上使用开发工具("观察控制台")时,该页面是"打开的",并且在控制台保持打开时不会关闭。

通过删除"persistent": false,您的代码将被执行。

但正如文档中所建议的那样,您应该尽可能多地使用事件页面,因此请查看生存期文档,了解与后台页面通信的不同方式,从而执行所需的代码。

这是因为清单中的"persistent": false

这描述了一个事件页面,也就是说,如果页面空闲超过几秒钟,Chrome可以随意卸载,只跟踪注册的事件处理程序。

事件页面的注释明确提到:

如果扩展使用window.setTimeout()window.setInterval(),请改用报警API如果事件页面关闭,基于DOM的计时器将不会被执行

如果你打开后台页面的开发工具窗口,它将不会被卸载,从而导致你的代码正确执行。


您可以切换到使用chrome.alarms API,但在此之前,请仔细阅读事件页面文档。您需要了解所有的限制:例如,由于页面已卸载,变量中的所有本地状态都将丢失。如果需要持久化状态,则需要使用存储API。

如果这对您的目的来说太复杂了,请删除"persistent": false以恢复到正常的背景页。