SaSquadge
SaSquadge

Reputation: 219

Using onKeyDown Chrome App

I have a question for you guys I'm not 100% sure how to implement this

chrome.app.window.onKeyDown = function(e) { 
  if (e.keyCode == 27 /* ESC */) { e.preventDefault(); }
};

I have my manifest going to my main.js file and in that file is

chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create('browser.html', {
    state: "fullscreen"
  });
});

How do I add that OnKeyDown to my main.js to get it to work? Or do I need to put that function into another file? Any help would be appreciated

Upvotes: 3

Views: 506

Answers (2)

Sergey Shevchenko
Sergey Shevchenko

Reputation: 1887

Try this:

chrome.app.runtime.onLaunched.addListener(function() {
  chrome.app.window.create(
    'browser.html', 
    {state: "fullscreen"}, 
    function(win) {
      win.contentWindow.onKeyDown = function(e) ...
    }
  );
});

Alternatively, you can link another script from your HTML:

browser.html:

...
<script src="xyz.js"></script>

And reference the same window object from xyz.js as:

chrome.app.window.current().onKeyDown = ...

Upvotes: 3

Marc Rochkind
Marc Rochkind

Reputation: 3740

I don't see chrome.app.window.onKeyDown in the Chrome API documentation.

The DOM window is available as win.contentWindow (not as win), assuming win is the argument to the chrome.app.window.create callback function. That's the window to which you should add a listener, using the addListener function. I'm not sure that onKeyDown as a property (...onKeyDown = function...) is defined.

It makes no difference whether you add the listener in the background.js page or the page referenced from the HTML file. I would think that the latter would be better, as a keydown event is only relevant to the user interface, not the background page. Also, whatever actions you take when a key is pressed probably are for the app page, not the background page.

Upvotes: 1

Related Questions