javascript - chrome.idle 在 chrome 扩展中未定义

标签 javascript google-chrome google-chrome-extension

我正在尝试在 Chrome 中实现简单的空闲检测。 我使用此权限创建了一个扩展:

"permissions": [
    "webNavigation",
    "storage",
    "tabs",
    "*://*/*",
    "idle"
],
"background": {
    "scripts": ["js/background.js"]
},
"content_scripts": [
    {
        "run_at": "document_start",
        "matches": [
            "*://*/*"
        ],
        "css": [
            "css/content.css"
        ],
        "js": [
            "js/jquery.min.js",
            "js/content.js"
        ]
    }
]

在 content.js 中

$(function () {

  console.log('init idle detection');
   chrome.idle.queryState(5, function(newState){
     //"active", "idle", or "locked"
     if(newState === "idle"){ alert(newState);    }
  });


   ...init other things...

});

但是,chrome.idle 始终未定义。

最佳答案

根据documentation ,内容脚本无法访问idle API。在后台脚本(或弹出脚本)中使用它并通过消息传递与内容脚本进行通信。

来自documentation :

Content scripts can access Chrome APIs used by their parent extension by exchanging messages with the extension. They can also access the URL of an extension's file with chrome.runtime.getURL() and use the result the same as other URLs.

//Code for displaying <extensionDir>/images/myimage.png:
var imgURL = chrome.runtime.getURL("images/myimage.png");  
document.getElementById("someImage").src = imgURL;

Additionally, content script can access the following chrome APIs directly:

  • i18n
  • storage
  • runtime:
    • connect
    • getManifest
    • getURL
    • id
    • onConnect
    • onMessage
    • sendMessage

Content scripts are unable to access other APIs directly.

(最后一行添加粗体)

关于javascript - chrome.idle 在 chrome 扩展中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56025204/

相关文章:

javascript - 隐藏最近的行 anchor 标记jquery

javascript - Chrome 扩展 - 使用 javascript 定期运行并永久记录数据

google-chrome - 通过 Google Chrome 扩展程序管理 cookie

javascript - 如何从react中的渲染函数返回一个空的jsx元素?

javascript - 为什么 Lodash 包装器不适用于 forEach?

javascript - 是否可以修改 Location 对象的现有属性,例如 "location.href"?

html - Chrome 打印预览错误

javascript - Chrome 丰富通知 - 如何使用

google-chrome-extension - 似乎无法让 chrome.contextMenus.onClicked 在 Chrome 扩展程序中触发

javascript - 如何使用 .search() 方法搜索字符串中的多个变量