0

I have this code:

 <?php
    /*
      creating a database
    */
    echo "<script>window.close();</script>";
?>

In the end I'm trying to close the current window, but I have this error: Scripts may close only the windows that were opened by it. The window is opened physically. Could you help me with solution?

Catalina
  • 95
  • 2
  • 12

2 Answers2

4

Imagine two pages, a.php and b.php.

b.php is the same in both examples:

<script>window.close();</script>

This example HTML will NOT work (a.php):

<a href="b.php">open b.php</a>

Now, this will work (a.php again):

<a href="#" onclick="window.open('b.php');return false">open b.php</a>

The reason why. Because Javascript (should) only be able to close a window that it has opened.

The first example HTML is a standard a href link. No Javascript used.

In the second example, a browser window is opened with Javascript, which can then be closed by Javascript.

PHP is a sever side script and has nothing to do with it at all. Would be best if the PHP tag was removed from the question.

Tigger
  • 8,980
  • 5
  • 36
  • 40
1

Few things to note here. With PHP you can not close users browser. PHP runs on the server. But with some javascript(as you have used) since it runs on the users browser.

In JS for you to close a window, that window needs to be opened by the script. For you to use window.close() the window needs to be opened by your script.

For example you can create a window using window.open() and using that handler you can close it as well.

If this is on a ajax call it also depends on the whether the parent page allow pop up as well.

var win;
function openWindow(){
  win= window.open('www.stackoverflow.com', 'stackoverflow');
}

function closeWindow(){
  win.close();
}


function close(){
  window.close();
}
<button onClick='openWindow'>Open Stackoverflow</button> 
<button onClick='closeWindow'>Close Stackoverflow</button> 
<button onClick='close'>Close Current window</button> 
udnisap
  • 899
  • 1
  • 10
  • 19