【问题标题】:my chrome "sleep" extension does not seem to run我的 chrome "sleep" 扩展似乎没有运行
【发布时间】:2020-12-30 18:55:39
【问题描述】:

我对 javascript 和 chrome 扩展非常陌生,对编程也很陌生。

我的 manifest.json :

{
    "name": "GetUp aSec",
    "version": "1.0",
    "description": "Be healthy, get up!",
    "manifest_version": 2,
    "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": [
                "content.js"
            ]
        }
    ],
    "browser_action": {
        "default_popup": "popup.html",
        "default_icon": "icon.png"
    },
    "background": {
        "scripts": [
            "background.js"
        ]
    }
}

我的 background.js 是我在网上找到的一个函数,它被承诺比正常的睡眠函数运行更顺畅 然后它每 52 分钟发送一条消息。

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

while (true) {
    sleep(52000 * 60).then(() => {
        chrome.tabs.query({ currentWindow: true, active: true },
            function (tabs) {
                chrome.tabs.sendMessage(tabs[0].id, 'its been 52 minutes! you should take a break.')
            })
    });
}

我的 content.js 只是一个监听器,希望能提醒消息。

chrome.runtime.onMessage.addListener(function (request) {
    alert(request)
})

当我将它添加到 chrome 时,它​​不会给我任何错误,但它也不会做任何事情。有什么帮助吗??

【问题讨论】:

  • while (true) { /*no control flow statements here*/ 杀死计算机。

标签: javascript google-chrome-extension sleep


【解决方案1】:

打开 Chrome 的任务管理器,您会看到您的扩展程序正在消耗 100% 的 CPU 并陷入无休止的 while 循环。

切换到 async/await 语法以实际暂停循环体

(async () => {
  while (true) {
    await sleep(52 * 60e3);
    chrome.tabs.query({currentWindow: true, active: true}, tabs => {
      chrome.tabs.sendMessage(tabs[0].id,
        "It's been 52 minutes! You should take a break.");
    });
  }
})();

更好的是,让您的后台脚本仅按需加载 ("persistent": false) 并使用chrome.alarms API 而不是无限循环和 setTimeout。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-19
    • 1970-01-01
    • 2018-07-05
    • 2020-10-07
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    相关资源
    最近更新 更多