javascript - Google chrome - 扩展程序 chrome 空闲时不起作用

标签 javascript google-chrome google-chrome-extension chromium

出现错误:未捕获类型错误:无法读取未定义的属性“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?)

enter image description here

最佳答案

让扩展程序打开网站并不会神奇地授予该网站使用 Chrome 扩展程序 API 的权利。

  1. 最简单的是将 index.html 作为扩展文件的一部分。然后就可以使用API​​了,但是要注意Chrome's CSP (您不能使用内联脚本)。

  2. 如果您的目标是专门提供对 Chrome API 的网页访问,则该网页将需要与扩展程序通信。

    many methods for that ,例如"externally_connectable" ,或者通过上下文脚本和共享 DOM 进行对话。

无论如何:chrome.idle只能从扩展程序自己的页面调用,包括但不限于后台页面。

此外,请在扩展程序中使用 chrome.windows.createchrome.tabs.create 而不是 window.open。它不需要特殊权限。

关于javascript - Google chrome - 扩展程序 chrome 空闲时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35173027/

相关文章:

javascript - 在多个 chrome.storage API 调用中防止竞争条件的最佳方法?

javascript - 争论异步 chrome.history 调用

javascript - Footable doSort 根本不起作用

javascript - 如何将 <li> 附加到 <ul> 并同时使用 jquery 在 <li> 上设置 css

CSS::第一行选择器 Chrome

html - 防止 google chrome 缓存 html 页面

google-chrome-extension - 在Dart中创建Web客户端

javascript - 在另一个函数中传递对象

javascript - Gridview 编辑项模板中无法识别文本框

html - 为什么现代 Web 浏览器的代码库如此庞大?