核心:要使window.close在Firefox中有效,必須先設(shè)置window.open
對(duì)于最常用的關(guān)閉窗口鏈接,都比較熟悉,使用的Javascript函數(shù)就是:window.close(),寫(xiě)完后在IE下測(cè)試,完全搞定;當(dāng)你用Mozilla內(nèi)核的瀏覽器打開(kāi)時(shí),點(diǎn)擊關(guān)閉窗口按鈕,你會(huì)發(fā)現(xiàn)事件并不會(huì)像你想象的那么順利,窗口根本就是無(wú)動(dòng)于衷(真痛恨瀏覽器的兼容性吧,哈哈,淡定,沒(méi)有瀏覽器的兼容性,又怎么會(huì)有前端開(kāi)發(fā)這個(gè)職業(yè)呢),這并不是Mozilla內(nèi)核瀏覽器不支持window.close()這個(gè)方法(打開(kāi)W3CSCHOOL,你會(huì)發(fā)現(xiàn)在Firefox 1.0就已經(jīng)支持了),那到底是什么原因引起Firefox沒(méi)有執(zhí)行這段代碼呢(準(zhǔn)確地說(shuō)應(yīng)該是執(zhí)行了,但沒(méi)有產(chǎn)生預(yù)期的效果而已,本人一直堅(jiān)信:就目前這技術(shù),機(jī)器是不會(huì)騙人的,一切還是人為原因)?
經(jīng)過(guò)Google一翻,在一篇名為:在Firefox 2.0中無(wú)法用Javascript關(guān)閉父窗口(原名:Cannot close parent window using javascript in Firefox 2.0)中找到真正的原因,其中有個(gè)網(wǎng)友直接使用下面的代碼的(問(wèn)題是:Firefox 2.0以下執(zhí)行,但2.0無(wú)效):
function closeWindow() {
window.open('','_parent','');
window.close();
}
一位很了解這個(gè)問(wèn)題的網(wǎng)友給出講解并貼出了原因:它當(dāng)然不會(huì)關(guān)閉,如果在window.open方法中不添加URL參數(shù)照樣執(zhí)行,但是下面的一行并不會(huì)執(zhí)行或不會(huì)做任何事情。下面的稍微變化的代碼指出的close()方法常見(jiàn)的錯(cuò)誤―close()方法不能關(guān)閉非Javascript腳本打開(kāi)的窗口(原文: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打開(kāi)一個(gè)窗口,這時(shí)你才可以使用window.close去關(guān)閉它,相反如果你通過(guò)常規(guī)鏈接打開(kāi)的窗口,window.close根本就關(guān)閉不了它,需要額外的用戶(hù)權(quán)限;這比直接使用關(guān)閉按鈕更令人討厭…(原文: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…),原來(lái)上面的兩段代碼都只針對(duì)使用window.open打開(kāi)的窗口,才能執(zhí)行window.close關(guān)閉,而對(duì)于URL鏈接新開(kāi)的窗口,必須要額外的用戶(hù)權(quán)限(UniversalBrowserWrite privilege),其實(shí)只要在執(zhí)行關(guān)閉窗口之前加上:
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
這段代碼即可,具體說(shuō)明參見(jiàn)Mozilla官網(wǎng)的“如何使用擴(kuò)展權(quán)限”(Using Expanded Privileges)