The NoteBook of EricKong

  BlogJava :: 首页 :: 联系 :: 聚合  :: 管理
  611 Posts :: 1 Stories :: 190 Comments :: 0 Trackbacks

核心:要使window.close在Firefox中有效,必须先设置window.open

对于最常用的关闭窗口链接,都比较熟悉,使用的Javascript函数就是:window.close(),写完后在IE下测试,完全搞定;当你用Mozilla内核的浏览器打开时,点击关闭窗口按钮,你会发现事件并不会像你想象的那么顺利,窗口根本就是无动于衷(真痛恨浏览器的兼容性吧,哈哈,淡定,没有浏览器的兼容性,又怎么会有前端开发这个职业呢),这并不是Mozilla内核浏览器不支持window.close()这个方法(打开W3CSCHOOL,你会发现在Firefox 1.0就已经支持了),那到底是什么原因引起Firefox没有执行这段代码呢(准确地说应该是执行了,但没有产生预期的效果而已,本人一直坚信:就目前这技术,机器是不会骗人的,一切还是人为原因)?

经过Google一翻,在一篇名为:在Firefox 2.0中无法用Javascript关闭父窗口(原名:Cannot close parent window using javascript in Firefox 2.0)中找到真正的原因,其中有个网友直接使用下面的代码的(问题是:Firefox 2.0以下执行,但2.0无效):

function closeWindow() {
window.open('','_parent','');
window.close();
}

一位很了解这个问题的网友给出讲解并贴出了原因:它当然不会关闭,如果在window.open方法中不添加URL参数照样执行,但是下面的一行并不会执行或不会做任何事情。下面的稍微变化的代码指出的close()方法常见的错误―close()方法不能关闭非Javascript脚本打开的窗口(原文:Yes, that doesn’t do anything. If I change the missing URL in the window.open command to an actual page, it executes but then the next line doesn’t run or doesn’t do anything. The following variation gives the usual script error for the close() method in this scenario — can’t close a window not opened by a script):

function closeWindow() {
newwin = window.open(location.href,'_parent','');
newwin.close();
}

如果你使用window.open打开一个窗口,这时你才可以使用window.close去关闭它,相反如果你通过常规链接打开的窗口,window.close根本就关闭不了它,需要额外的用户权限;这比直接使用关闭按钮更令人讨厌…(原文:If you launch the initial Firefox window using window.open, then window.close should work on it. However, if it is launched from a regular URL, then as you know it doesn’t work. There is a way to ask the user for extra permissions. However, that might be more annoying than leaving the window open…),原来上面的两段代码都只针对使用window.open打开的窗口,才能执行window.close关闭,而对于URL链接新开的窗口,必须要额外的用户权限(UniversalBrowserWrite privilege),其实只要在执行关闭窗口之前加上:

netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");

这段代码即可,具体说明参见Mozilla官网的“如何使用扩展权限”(Using Expanded Privileges)

posted on 2010-10-19 13:08 Eric_jiang 阅读(2842) 评论(0)  编辑  收藏 所属分类: JavaScript

只有注册用户登录后才能发表评论。


网站导航: