Google chrome - 分机 chrome 闲置不工作

Google chrome - extension chrome idle not working

出现错误: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.

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

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

    many methods for that, for example "externally_connectable",或通过上下文脚本交谈并共享 DOM。

任何情况下:chrome.idle只能在扩展自身页面调用,包括但不限于后台页面。

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