Roland
Roland

Reputation: 57

window.close() function in javascript

I have a problem with window.close() function. I have a simple HTML script:

<body>
<a href="http://www.gmail.com" class="one">gmail</a><br />
<a href="http://www.google.com" class="one">google</a><br />

<input type="submit" id="submit" name="submit" value="submit">

<script src="project.js"></script>
</body>

I want to open the above url's in different windows. Once the url's are loaded, the windows should close itself without any alerts. The below javascript code lets the url's open in different windows. But it closes only 'google.com' and the html webpage. The 'gmail' website remains open.

var submit = document.getElementById("submit");

submit.onclick = function() {
    var getLinks = document.getElementsByClassName("one");

    for(var i=0; i<=(getLinks.length-1); i++) {
        window.open(getLinks[i]);
        getLinks[i].onload = window.close();
    }
}

What am I missing in this code. Any help would be appreciated. Note: the links are only for test.

Upvotes: 1

Views: 2564

Answers (4)

StevenSong
StevenSong

Reputation: 1

A page to B page

window.open('B.html', '_blank');
window.open('','_self').close();

page close

window.open('','_self').close();

Upvotes: 0

user3996249
user3996249

Reputation:

Check this out:

function openWin() {
    myWindow = window.open("http://google.com", "myWindow", "width=200, height=100");    // Opens a new window
}

function closeWin() {
    myWindow.close();                                                  // Closes the new window
}

Easily found here: http://www.w3schools.com/jsref/met_win_close.asp

Fiddle: http://jsfiddle.net/zc2g7nkr/

It works fine in Chrome and i do not have to allow to block pop-ups.

Upvotes: 1

Sam1604
Sam1604

Reputation: 1489

The problem is that certain browsers do not allow you to close a window using javascript.

There are bugs that prevent it - specifically that the browser won't let code from one website close a window that is opened to a different website.

var win = window.open("http://www.google.com", '1366002941508','width=500,height=200,left=375,top=330');

setTimeout(function () { win.close();}, 3000);

Here is a DEMO

It works fine in Firefox when you allowing popup,

It opens a popup in chrome but it do not allow you to close a window using javascript.

Upvotes: 0

Christoph
Christoph

Reputation: 2053

It's not possible any longer to close a window you have not created.

Take a look at this window.close and self.close do not close the window in Chrome

Upvotes: 0

Related Questions