Ben Holness
Ben Holness

Reputation: 2717

Can I detect whether a key is pressed when a window gains focus?

I am writing a little page that opens a URL in a new tab, waits for it to close, and then opens another URL in a new tab and so on through a list of URLs.

To get the next URL to open when the last one gets closed, I tried using:

let new_window = window.open(url,'_blank');

new_window.onbeforeunload = function(event) {
    openNextWindow();                            
}

but it didn't seem to work. I then switched to having

window.onfocus = function(event){
    if (event.explicitOriginalTarget === window) {
         openNextWindow();
    }
}

Which works great, but there's no way to cancel it once it has started (other than by closing the tab), as every time you go back to the page, it opens a new tab.

So I am wondering if I detect whether a key is currently pressed from the onfocus event, then I can say e.g. "Hold down x when returning to the tab to prevent the next URL from being opened", and have some code on the lines of:

window.onfocus = function(event) {
    if(!keyIsCurrentlyPressed("x") && event.explicitOriginalTarget === window){
         openNextWindow();
    }
}

I do not know how I can implement keyIsCurrentlyPressed(key) though, and my searches are flooded with results pertaining to detecting when it is pressed (e.g. keypress event), not whether it is currently pressed.

Upvotes: 0

Views: 142

Answers (1)

James
James

Reputation: 22246

This idea is to quickly install a keydown listener when focus happens, and give it a short time (here 500ms, possibly adjustable) to detect if X is being held down. The event.explicitOriginalTarget was not working for the example so I've commented it out.

let xPressed = false;
let detectTimeout = 500;

window.onfocus = function(event) {
  const keyDownFn = (e) => {
    if (e.key === "x") xPressed = true;
  }
  document.addEventListener("keydown", keyDownFn);
  setTimeout(() => {
    document.removeEventListener("keydown", keyDownFn)
    if (!xPressed) { // && event.explicitOriginalTarget === window) {
      console.log("open next window");
    } else {
      console.log("you pressed x");
    }
  },  detectTimeout);
}

Upvotes: 1

Related Questions