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 閱讀(2863) 評論(0)  編輯  收藏 所屬分類: JavaScript
          主站蜘蛛池模板: 平邑县| 宁津县| 尼勒克县| 神农架林区| 沽源县| 庆云县| 沭阳县| 渝中区| 河津市| 莱阳市| 保靖县| 望谟县| 靖远县| 清徐县| 乌审旗| 黑山县| 太仓市| 肃北| 观塘区| 富宁县| 甘洛县| 义马市| 绩溪县| 易门县| 沙洋县| 彰武县| 马公市| 谷城县| 大化| 民权县| 兴义市| 潞城市| 岑溪市| 乌兰察布市| 彝良县| 保德县| 松江区| 阜南县| 浦城县| 肥西县| 临清市|