Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate CTRL+W onclick on element

Tags:

javascript

Hei guys, i'm trying to simulate ctrl+w on click on image. So i have:

<img id="target" src="something.png"/>

And i try to add a click event on this image which call a function that simulate ctrl+w from keyboard.

I thought it should be something like this:

function closeWindow(){
            var theObject = document.getElementById("target");

            var pressEvent = document.createEvent ("KeyboardEvent");
            pressEvent.initKeyEvent("keypress", true, true, window, true, false, false, false, 87, 0);
            theObject.dispatchEvent(pressEvent);
        }

The simulated ctrl+w should have the same event as ctrl+w pressed by user from keyboard, i only need to close the tab by pressing a button/image.

AND NO, i cant use window.close(); as this method doesnt work if the page wasnt created by script.

Where am i wrong?

like image 905
OzZie Avatar asked Jul 03 '26 08:07

OzZie


1 Answers

You can't send fake keystrokes to the browser chrome from a webpage.

Even if you could, it would make the restructions on window.close pretty pointless if you could bypass them by faking keystrokes.

You can't close a window/tab you didn't open. It doesn't belong to you.

like image 125
Quentin Avatar answered Jul 05 '26 21:07

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!