我正在尝试在 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/