Javascript Chrome 打包应用程序中的按钮

Javascript Button in Chrome Packaged App

我正在开发 chrome 应用程序,但似乎无法使 html/JS 按钮正常工作。在我的 background.js 文件中,我有以下代码:

chrome.app.window.create('window.html', {
        // TODO- pick a more appropriate window size, create UI
        'bounds': {
            'width': 400,
            'height': 500
        }
    }, function(appWin){
        pageDocument = appWin.contentWindow.document;
        pageDocument.getElementById("Listen").onclick = function(){
            // do stuff
        });
});

我最初尝试只使用 "document" 而没有从内容 window 中获取 pageDocument 对象,但没有成功,因为 "document" 未定义。但是,这个新代码甚至无法让我打开应用程序,所以我很难找出问题所在。这绝对是 getElementById.onclick 函数中的某些内容,因为如果我注释掉该特定部分,应用程序打开时没有错误消息 - 但我不确定出了什么问题。

Chrome CSP 禁止尝试在任何元素上分配 onclick,因为这算作内联代码。

您应该附加一个事件侦听器,它在 window.html 本身更有意义。

// window.js, include in window.html

// Required to ensure #Listen exists
document.addEventListener('DOMContentLoaded', function () {
  // Attach event listeners, not inline onclick attribute
  document.getElementById("Listen").addEventListener("click", function() {
    /* your event processing */
  });
});