简体   繁体   English

Chrome打包应用中的Javascript按钮

[英]Javascript Button in Chrome Packaged App

I'm working on a chrome app but can't seem to get html/JS buttons working. 我正在开发Chrome应用程序,但似乎无法使html / JS按钮正常工作。 In my background.js file, I have the following code: 在我的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
        });
});

I had at first tried just using "document" without getting the pageDocument object from the content window and that didn't work, as "document" was undefined. 起初,我尝试仅使用“文档”而不从内容窗口获取pageDocument对象,但这没有用,因为“文档”未定义。 However, this new code won't even let me open the application, so I'm having trouble figuring out what's wrong. 但是,这个新代码甚至都不允许我打开应用程序,因此我很难找出问题所在。 It's definitely something in the getElementById.onclick function, as the app opens with no error messages if I comment that specific part out- but I'm not sure what's wrong. 这绝对是getElementById.onclick函数中的内容,因为如果我注释掉特定部分,则应用程序打开时不会显示任何错误消息-但我不确定出什么问题。

Trying to assign onclick on any element is forbidden by Chrome CSP, as this counts as inline code. Chrome CSP禁止尝试在任何元素上分配onclick ,因为这被视为内联代码。

You should be attaching an event listener, and it would make much more sense in window.html itself. 您应该附加一个事件侦听器,在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 */
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM