出现错误:未捕获类型错误:无法读取未定义的属性“queryState”
如何从我的代码运行扩展程序 ( 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
}
背景.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/