js控制浏览器关闭

由于在脚本中使用了 window.close(), 当前非弹出窗口在最新版本的chrome和firefox里总是不能关闭,而在 IE中是可以关闭的 。

在console中弹出提示"Scripts may close only the windows that were opened by it" (脚本只能关闭它所打开的窗口),[如下图所示] , 不明白是什么原因。

经过一段时间的折腾。终于明白了问题所在。

首先,什么是非弹出窗口呢?

非弹出窗口,即是指(opener=null 及 非window.open()打开的窗口,比如URL直接输入的浏览器窗体, 或由其它程序调用产生的浏览器窗口)。

其次,window.close() 怎么理解呢?

 

由 https://developer.mozilla.org/en-US/docs/Web/API/window.close可知:

Closes the current window, or the window on which it was called.
When this method is called, the referenced window is closed.

This method is only allowed to be called for windows that were opened by a script using thewindow.open() method. If the window was not opened by a script, the following error appears in the JavaScript Console: Scripts may not close windows that were not opened by script.

Examples

Closing a window opened with window.open()

This example demonstrates how to use this method to close a window opened by script callingwindow.open().

<script type="text/javascript">
//Global var to store a reference to the opened window
var openedWindow;

function openWindow()
{
  openedWindow = window.open(‘moreinfo.htm‘);
}

function closeOpenedWindow()
{
  openedWindow.close();
}
</script>

Closing the current window

When you call the window object‘s close() method directly, rather than calling close() on a windowinstance, the browser will close the frontmost window, whether your script created that window or not.

<script type="text/javascript">
function closeCurrentWindow()
{
  window.close();
}
</script>

在某些实际应用中,window.close() and self.close() 是不能关闭非弹出窗口(opener=null及非window.open()打开的窗口)。

方案:

1.

function closeWindows() {
         var browserName = navigator.appName;
         var browserVer = parseInt(navigator.appVersion);
         //alert(browserName + " : "+browserVer);

         //document.getElementById("flashContent").innerHTML = "<br>&nbsp;<font face=‘Arial‘ color=‘blue‘ size=‘2‘><b> You have been logged out of the Game. Please Close Your Browser Window.</b></font>";

         if(browserName == "Microsoft Internet Explorer"){
             var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false;
             if (ie7)
             {
               //This method is required to close a window without any prompt for IE7 & greater versions.
               window.open(‘‘,‘_parent‘,‘‘);
               window.close();
             }
            else
             {
               //This method is required to close a window without any prompt for IE6
               this.focus();
               self.opener = this;
               self.close();
             }
        }else{
            //For NON-IE Browsers except Firefox which doesnt support Auto Close
            try{
                this.focus();
                self.opener = this;
                self.close();
            }
            catch(e){

            }

            try{
                window.open(‘‘,‘_self‘,‘‘);
                window.close();
            }
            catch(e){

            }
        }
    }

2.

<script type="text/javascript">
function closeWP() {
 var Browser = navigator.appName;
 var indexB = Browser.indexOf(‘Explorer‘);

 if (indexB > 0) {
    var indexV = navigator.userAgent.indexOf(‘MSIE‘) + 5;
    var Version = navigator.userAgent.substring(indexV, indexV + 1);

    if (Version >= 7) {
        window.open(‘‘, ‘_self‘, ‘‘);
        window.close();
    }
    else if (Version == 6) {
        window.opener = null;
        window.close();
    }
    else {
        window.opener = ‘‘;
        window.close();
    }

 }
else {
    window.close();
 }
}
</script>

http://stackoverflow.com/questions/57854/how-can-i-close-a-browser-window-without-receiving-the-do-you-want-to-close-thi

老式关闭当前页面js
window.opener=null;
window.open(‘‘,‘_self‘);
window.close();

但是关闭 Chrome 浏览器会有问题

Scripts may close only the windows that were opened by it.

搜了半天居然没有答案;所以我自己发上来以便别人需要

关闭当前页面js

open(location, ‘_self‘).close();

其它参考:

A:

https://productforums.google.com/forum/#!topic/chrome/GjsCrvPYGlA

‘p‘ is new window that i opened, i‘m using jquery to test what browser you have, this is example when i open new window, populate it, call print dialog, then close it

it‘s not solution to original problem but just in case someone find it useful

if ( $.browser.msie ) p.location.reload();  //for IE if you want print dialog to show 
p.window.print(); 
if ( $.browser.msie || $.browser.opera || $.browser.mozilla) p.window.close(); 
else p.window.self.close(); //for chrome

B:

Ordinary javascript cannot close windows willy-nilly. This is a security feature, introduced a while ago, to stop various malicious exploits and annoyances.

From the latest working spec for window.close():

The close() method on Window objects should, if all the following conditions are met, close the browsing context A:

  • The corresponding browsing context A is script-closable.
  • The browsing context of the incumbent script is familiar with the browsing context A.
  • The browsing context of the incumbent script is allowed to navigate the browsing context A.

A browsing context is script-closable if it is an auxiliary browsing context that was created by a script(as opposed to by an action of the user), or if it is a browsing context whose session history contains only one Document.

This means, with one small exception, javascript must not be allowed to close a window that was not opened by that same javascript.

Chrome allows that exception -- which it doesn‘t apply to userscripts -- however Firefox does not. The Firefox implementation flat out states:

This method is only allowed to be called for windows that were opened by a script using the window.open method.



If you try to use window.close from a Greasemonkey / Tampermonkey / userscript you will get:
Firefox: The error message, "Scripts
may not close windows that were not opened by script.
"
Chrome: just silently fails.


The long-term solution:

The best way to deal with this is to make a Chrome extension and/or Firefox add-on instead. These can reliably close the current window.

However, since the security risks, posed by window.close, are much less for a Greasemonkey/Tampermonkey script; Greasemonkey and Tampermonkey could reasonably provide this functionality in their API (essentially packaging the extension work for you).
Consider making a feature request.


The hacky workarounds:

Chrome is currently vulnerable to the "self redirection" exploit. So code like this will currently work in Tampermonkey scripts:

open(location, ‘_self‘).close();

This is buggy behavior, IMO, and is liable to be blocked by future releases of Chrome, so use this hack with that in mind.

Firefox is secure against that exploit. So, the only javascript way is to cripple the security settings, one browser at a time.

You can open up about:config and set
allow_scripts_to_close_windows to true.

If your script is for personal use, go ahead and do that. If you ask anyone else to turn that setting on, they would be smart, and justified, to decline with prejudice.

There currently is no equivalent setting for Chrome.

C: 

http://stackoverflow.com/questions/19761241/window-close-and-self-close-do-not-close-the-window-in-chrome

 

From my observation, this update fixed the issue on using window.close() to close the popup window. You will see this in the console when it fail, "Scripts may close only the windows that were opened by it.". That means The hacky workarounds (Brock Adams‘s answer) may not work in the latest release.

So, in the previous Chrome released builds, the below code block may worked but not with this update.

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

For this update, you have to update your code accordingly to close the popup window. One of the solution is to grab the popup window id and use

chrome.windows.remove(integer windowId, function callback)

method to remove it. Chrome extension windows API can be found at chrome.windows.

Actually my chrome extension MarkView was facing this issue and I had to update my code to make it work for this Chrome Update. By the way, MarkView is tool to read and write Awesome Markdown Files, it provides features including Content Outline, Sortable Tables and code block syntax highlight with line number.

I also created this post, any comments are welcome.

参考网址:

https://developer.mozilla.org/en-US/docs/Web/API/window.close

https://productforums.google.com/forum/#!topic/chrome/GjsCrvPYGlA

http://stackoverflow.com/questions/19761241/window-close-and-self-close-do-not-close-the-window-in-chrome

本文地址:http://blog.csdn.net/aerchi/article/details/41441429

时间: 2024-12-15 05:14:20

js控制浏览器关闭的相关文章

js 判断浏览器关闭事件 兼容所有浏览器

无论是从页签处关闭浏览器,还是关闭整个浏览器窗口,无论是 ie11,火狐,谷歌,苹果,还是ie6,都能兼容的浏览器关闭事件监听 在网上搜索了一天,虽然网上也有之类的代码,但是太繁琐,有时候还不可用.我也是在原有基础上修改的.经过了上述的浏览器测试,如果有不兼容的,欢迎提出意见一起学习. ? <script type="text/jscript" src="jquery-1.10.2.min.js"></script> <script t

js 监控浏览器关闭事件

代码如下: <!DOCTYPE html> <html> <head> <title>监控浏览器关闭事件</title> </head> <style type="text/css"> </style> <body> <div id="create_order"> </div> </body> </html> &

scripts may close only the windows that were opened by it 浏览器JS控制无法关闭当前页面

不是window.open形式打开的子页面用js的window.close在chrome下就会提示关不了. 网上的很多解决方法都是把当前页面为空,在IE和360浏览器也不能直接关闭页面,翻到stack overflow的解决方案: if(navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Chrome") != -1) { open(location, '_self

js控制浏览器全屏

HTML 5中的full screen,目前可以在除IE和opera外的浏览器中使用 ,有的时候用来做全屏API,游戏呀,等都很有用.先看常见的API element.requestFullScreen() 作用:请求某个元素element全屏 Document.getElementById("myCanvas").requestFullScreen() 这里是将其中的元素ID去请求fullscreen 退出全屏 document.cancelFullScreen() Document

js 控制浏览器窗口大小

//打开一个新窗口并设置其大小window.open('index.html','','width=450,height=750,location=no,menubar=no,status=no,toolbar=no' );//不询问是否关闭window.opener=null;window.open('','_self');//关闭自己的窗口window.close();

js关闭浏览器窗口及检查浏览器关闭事件

js关闭浏览器窗口,不弹出提示框.支持ie6+,火狐,谷歌等浏览器,下面以一个示例为大家详细介绍下具体的实现方法,感兴趣的朋友可以参考下 js关闭浏览器窗口 js关闭浏览器窗口,不弹出提示框.支持ie6+,火狐,谷歌等浏览器. <html> <head /> <body> <script type="text/javascript"> function closeWin(){ window.opener=null; window.open

JS弹出框、对话框、提示框,JS关闭窗口、关闭页面和JS控制页面跳转

一.JS弹出框.对话框.提示框 //====================== JS最常用三种弹出对话框 ======================== //1弹出对话框并输出一段提示信息 function ale() { //弹出一个对话框 alert("提示信息!"); } //2弹出一个询问框,有确定和取消按钮 function firm() { //利用对话框返回的值 (true 或者 false) if (confirm("你确定提交吗?")) { a

JS控制CSS3,添加浏览器兼容前缀

不同浏览器对于有些css3属性名字定义的时候,会带上特有的前缀,所以在css编写的时候,经常会一个属性写多个不同的前缀进行兼容.比如: div { transform: rotate(30deg); -ms-transform: rotate(30deg); /* IE 9 */ -webkit-transform: rotate(30deg); /* Safari and Chrome */ -o-transform: rotate(30deg); /* Opera */ -moz-trans

用JS实现控制浏览器F12与右键功能

本文出至:新太潮流网络博客 用JS实现控制浏览器F12与右键功能,防止恶意窃取代码,或其他直接复制进去就好 //禁用右键 document.oncontextmenu = function () { return false; }; //禁用开发者工具F12 document.onkeydown = function () { if (window.event && window.event.keyCode == 123) { event.keyCode = 0; event.return