收到错误:Uncaught TypeError: Cannot read property 'queryState' of undefined
如何从代码中运行扩展名(https://developer.chrome.com/apps/idle)?
manifest.json:
{
"name" : "Idle - Simple Example",
"version" : "1.0.1",
"description" : "Demonstrates the Idle API",
"background" : {
"scripts": ["background.js"]
},
"permissions" : [ "idle" ],
"browser_action" : {
"default_icon" : "sample-19.png"
},
"icons" : {
"16" : "sample-16.png",
"48" : "sample-48.png",
"128" : "sample-128.png"
},
"manifest_version": 2
}
background.js:
var history_log = [];
chrome.idle.onStateChanged.addListener(function(newstate) {
var time = new Date();
if (history_log.length >= 20) {
history_log.pop();
}
history_log.unshift({'state':newstate, 'time':time});
});
chrome.browserAction.onClicked.addListener(function() {
window.open('history.html', 'testwindow', 'width=700,height=600');
});
失败:在我的代码中获取chrome.idle.queryState,
http://localhost/index.html
:<html>
<script>
document.addEventListener('DOMContentLoaded', function() {
chrome.idle.queryState(5, function(state) {
var time = new Date();
alert("extension: " + state);
});
});
</script>
</html>
编辑:
它仅在我用作chrome-extension://时起作用,但如果我尝试从http://或https://使用它,则不起作用。我的目标是从http://或https://使其正常工作(或者如果可能,iFrame会以无形方式打开chrome-extension吗?)
最佳答案
打开扩展程序无法正常授予网站使用Chrome扩展程序API的权利。
最简单的方法是将index.html
作为扩展文件的一部分。然后,您可以使用API,但要注意Chrome's CSP(您不能使用内联脚本)。
如果您的目标是专门提供对Chrome API的网页访问权限,则该网页需要与扩展程序对话。
有many methods for that,例如"externally_connectable"
,或者通过上下文脚本和共享的DOM交谈。
无论如何:chrome.idle
只能从扩展程序自己的页面中调用,包括但不限于后台页面。
另外,请在扩展名中使用chrome.windows.create
或chrome.tabs.create
代替window.open
。它不需要特殊的权限。
关于javascript - Google Chrome-扩展程序Chrome闲置不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35173027/