URL 在 HTML 裡有各種寫法,而 JavaScript 讀取這些屬性時,各瀏覽器的行為還不一致。搞不清楚這件事,很容易在跨瀏覽器開發時踩坑。
相對 URL:
example.php
demo/example.php
./example.php
../../example.php
/example.php
絕對 URL:
https://jb51.net/example.php
https://jb51.net:80/example.php
https://jb51.net/example.php
HTML 中有大量屬性的值本身就是 URL。取得這些值有兩種途徑:
<a href="example.php" id="example-a">此時頁面絕對 URL 是 https://jb51.net/</a>
<script>
var oA = document.getElementById('example-a');
oA.href == 'https://jb51.net/example.php'; // 直接存取屬性:完整絕對 URL
oA.getAttribute('href') == 'example.php'; // getAttribute:原始屬性值
</script>
理想結果正是如此:直接存取屬性拿到完整絕對 URL,getAttribute 拿到原始寫法。但在當時的 A 級瀏覽器中,只有 Firefox 與 IE8 能穩定做到這點,其餘或多或少都有特殊行為。
多數瀏覽器的共同問題是:兩種方式都只回傳原始屬性值,而實務上我們往往需要的正是絕對 URL。
先看看 form 的 action 這類屬性:
<form action="example.php" id="example-form">
此時頁面絕對 URL 是 https://jb51.net/</form>
<script>
var oForm = document.getElementById('example-form');
// IE6、IE7、Safari、Chrome、Opera
oForm.action == 'example.php';
oForm.getAttribute('action') == 'example.php';
// 取得絕對 URL 的通用方案
getQualifyURL(oForm, 'action') == 'https://jb51.net/example.php';
getQualifyURL = function(oEl, sAttr){
var sUrl = oEl[sAttr], oD, bDo = false;
/*@cc_on
try{
bDo = @_jscript_version < 5.8 ? true : @false; // 是否 IE8 之前版本
}catch(e){ bDo = false; }
@*/
// 是否為 Safari、Chrome、Opera
if(/a/.__proto__=='//' || /source/.test((/a/.toString+''))
|| /^function \(/.test([].sort)){
bDo = true;
}
if(bDo){
oD = document.createElement('div');
oD.innerHTML = ['<a href="', sUrl, '"></a>'].join('');
sUrl = oD.firstChild.href;
}
return sUrl;
}
</script>
思路是借用瀏覽器自己解析 <a> 的能力,把相對路徑轉成絕對路徑,避開一堆手動拼接基準 URL 的麻煩。
在這兩個「史前」瀏覽器上還有一層轉折:兩種方式在 A、AREA、IMG 元素上取到的屬性值都是絕對 URL。所幸微軟為 getAttribute 提供了第二個參數可以指定取值模式,同時也順便解決了 IFRAME 與 LINK 元素兩種方法都回傳原始值的問題:
<link href="../../example.css" id="example-link">
<a href="example.php" id="example-a">此時頁面絕對 URL 是 https://jb51.net/</a>
<script>
var oA = document.getElementById('example-a'),
oLink = document.getElementById('example-link');
oA.href == 'https://jb51.net/example.php';
oA.getAttribute('href') == 'https://jb51.net/example.php';
oA.getAttribute('href', 2) == 'example.php';
oLink.href == 'example.php';
oLink.getAttribute('href') == 'example.php';
oLink.getAttribute('href', 4) == 'https://jb51.net/example.php';
</script>
總結一句:寫跨瀏覽器程式時,不要假設 href 與 getAttribute('href') 在所有環境下都回傳同樣的東西,最好一律走同一個轉絕對路徑的函式。