有某段用 window.open() 開啟新網頁的 JavaScript 程式,在 IE 如預期開出新網頁,但在 Chrome 裡卻開啟在新頁籤,害我被迷惑了一陣子,做完研究整理筆記備忘。

測試程式如下:線上版

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>window.open Test</title>
  <style>button{display:block;margin:3px}</style>
</head>
<body>
  <button onclick="testWinOpen1()">window.open() test 1</button>
  <button onclick="testWinOpen2()">window.open() test 2</button>
  <button onclick="testWinOpen3()">window.open() test 3</button>
  <script>
    var url = 'https://blog.darkthread.net';
    function testWinOpen1() {
      window.open(url)
    };
    function testWinOpen2() {
      window.open(url,'win2','width=320');
    }
    function testWinOpen3() {
      window.open(url,'win3','width=320,height=200');
    }
  </script>
</body>
</html>

我總共測了 IE、Chrome/Edge、Firefox 四種瀏覽器,歸納結果如下:

  1. window.open(url),未指定 width、height,各家瀏覽器都會在新頁籤開啟網頁
  2. window.open() 時指定 width 或 width/height,瀏覽器就會改成在新視窗開啟網頁
  3. 若只指定 width,Firefox、IE 會依指定寬度開啟新視窗;Chrome/Edge 則會無視 width 設定值,沿用瀏覽器目前的寬度開啟新視窗
  4. 若同時指定 width/height,所有瀏覽器都會依指定寬度及高度開啟新視窗

下圖可看出 Chrome 在只指定 width 時(test 2),新視窗與原視窗等寬,指定 width/height 時(test 3)才會用指定的尺寸(320x200)。

IE 只指定 width 時也會依指定寬度開新視窗:

最後回到一開始讓我迷惑的點。我遇到的案例是 window.open(url) 在 IE 開新視窗,在 Chrome 卻開在新頁籤,跟上述第一點的結論不同,理論上沒指定 width/height 時 IE 應該也開在新頁籤才對。

回頭檢查環境才恍然大悟,答案在 showModalDialog。

IE 的 window.open() 是在 showModalDialog 開的網頁裡執行,強制視窗沒有頁籤概念,當然只能開新視窗。而 Chrome 沒有 showModalDialog,window.open() 是在 IFrame 裡執行,適用第一條規則,開在新頁籤。

結案,收工。

Study of how to control browser to window.open() in new tab or new window.


Comments

Be the first to post a comment

Post a comment