【问题标题】:Google chrome - extension chrome idle not working谷歌浏览器 - 扩展浏览器空闲不工作
【发布时间】:2016-05-12 09:54:06
【问题描述】:

得到错误: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');
});

FAIL:在我的代码中获取 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?)

【问题讨论】:

  • 我想知道您在哪个页面上执行 DomContentLoaded 事件。是扩展的页面部分。
  • 我正在 index.html 中执行 DomContentLoaded 事件,这是网站的常规页面部分。

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


【解决方案1】:

让扩展程序打开网站并不会神奇地授予网站使用 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。它不需要特殊权限。

【讨论】:

  • 我需要在该页面中以https://example.com/phpetcetc 的身份启动它,我需要跟踪状态。为此,我该怎么办?
  • 它是一个 KIOSK 应用程序,我必须以 http:// 或 https:// 运行它,并且从那里我需要获取活动或空闲状态。不可能吗?或者还有其他方式使用 iframe 到本地扩展 url 作为 chrome-extension:// ?
  • 等等,自助服务终端应用程序?那你为什么要让它成为一个扩展,而不是一个应用程序?
  • 因为在 kiosk 应用程序中我使用的是 webRTC
  • 所以我必须在全屏信息亭触摸屏上需要 WebRTC + 空闲状态。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-17
  • 2014-07-24
  • 2016-06-08
  • 2012-04-21
相关资源
最近更新 更多