2017-05-07 77 views
1

我想使用戶的瀏覽器使用的按鈕(帶有url)是動態的。如果用戶使用Chrome,則鏈接將在新標籤中打開;但是,如果用戶使用IE,則該鏈接應在Chrome中打開。'onclick'事件在新標籤頁或其他瀏覽器中打開url

我無法在Chrome瀏覽器中下面的代碼工作,但這個工作在IE 9

我從一些其他職位得到有用的代碼。

下面將確定/檢查哪個瀏覽器用戶在:

function getInternetExplorerVersion() 
{ 
    var rv = -1; // Return value assumes failure. 

    if (navigator.appName == 'Microsoft Internet Explorer') 
    { 
     var ua = navigator.userAgent; 
     var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); 
     if (re.exec(ua) != null) 
      rv = parseFloat(RegExp.$1); 
    } 

    return rv; 
} 

上面代碼段工作正常。 我的代碼如下在IE中無縫地運行,但在Chrome中無法運行。

<input type="button" onclick="openURL()" value="Open Google"> 

<script> 
    function openURL() 
    { 
     var ver = getInternetExplorerVersion(); 
     var shell = new ActiveXObject("WScript.Shell"); 

    if (ver = -1) 
      shell.run("Chrome www.google.com"); 
     else 
      window.open('www.google.com','_blank'); 
    } 

</script> 
+0

嘗試使用完整的URL'的window.open( 'http://www.google.com');' –

+0

http://stackoverflow.com/a/13592045/3163306 – AvrilAlejandro

+0

@MantasČekanauskas這並不是雖然 – oozmac

回答

1

Chrome在該ActiveXObject行上提供了一個錯誤,因此您應該只將該代碼暴露給IE。假設ver總是給出比其他-1一些在IE中,你應該試試這個:

function openURL() { 
    var ver = getInternetExplorerVersion() 

    if (ver != -1) { 
    // IE 
    var shell = new ActiveXObject("WScript.Shell"); 
    shell.run("Chrome www.google.com"); 
    } else { 
    // other browsers 
    window.open('//www.google.com','_blank'); 
    } 
} 

當然鉻是讀你的代碼,你剛纔沒看到錯誤。按F12打開瀏覽器開發工具,然後轉到控制檯選項卡查看腳本錯誤。

+0

btw,我剛剛檢查在IE中,'getInternetExplorerVersion()'也在IE中返回-1 ...因此代碼不可靠。所以它似乎只適用於IE,因爲你的if語句是錯誤的。 – yezzz

+0

非常感謝你花時間解決這個案子。它在** CHROME **中效果很好。你是最好的 – oozmac

+0

不客氣。你是否修復了getInternetExplorerVersion函數?它在IE11中沒有給我正確的版本。另外,shell.run沒有工作,但這可能是一個activeX問題。 – yezzz

相關問題