简体   繁体   中英

Javascript Button in Chrome Packaged App

I'm working on a chrome app but can't seem to get html/JS buttons working. In my background.js file, I have the following code:

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. 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.

Trying to assign onclick on any element is forbidden by Chrome CSP, as this counts as inline code.

You should be attaching an event listener, and it would make much more sense in window.html itself.

// 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 */
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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