3

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?

Mwiza
  • 7,780
  • 3
  • 46
  • 42
OzZie
  • 523
  • 9
  • 21
  • http://stackoverflow.com/questions/19761241/window-close-and-self-close-do-not-close-the-window-in-chrome – apokryfos Oct 27 '15 at 16:22

1 Answers1

4

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    If i use ctrl+w from keyboard its working, i dont see any reason why i cant fake by code ctrl+w – OzZie Oct 27 '15 at 16:16
  • I think the browser doesnt know if i pressed em by user from keyboard or i simulated them from code, it just gets some code (87 + true - ctrlkey) and it should do the trick – OzZie Oct 27 '15 at 16:17
  • 1
    @OzZie The browser is not that stupid. It knows what came from a hardware keyboard and what came from javascript. – apokryfos Oct 27 '15 at 16:18
  • So you're saying that aint any way of closing current tab on all major browsers? – OzZie Oct 27 '15 at 16:21
  • 1
    @OzZie You can only close a window you've created. It's a strict security requirement from all major browsers. – apokryfos Oct 27 '15 at 16:25