[前端]利用a标签获取url里所需的内容

时间:2021-03-30 04:19:09
function parseURL(url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':',''),
host: a.hostname,
port: a.port,
query: a.search,
params: (function(){
var ret = {},
seg = a.search.replace(/^?/,'').split('&'),
len = seg.length, i = 0, s;
for (;i<len;i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(//([^/?#]+)$/i) || [,''])[1],
hash: a.hash.replace('#',''),
path: a.pathname.replace(/^([^/])/,'/$1'),
relative: (a.href.match(/tps?://[^/]+(.+)/) || [,''])[1],
segments: a.pathname.replace(/^//,'').split('/')
};
}

 获取file好像有错

 来源:http://james.padolsey.com/javascript/parsing-urls-with-the-dom/

iframe里获取父页面的url

function getParentUrl() {
var url = null;
if (parent !== window) {
try {
url = parent.location.href;
} catch (e) {
url = document.referrer;
}
}
return url;
}