为文档提供正确的URL或位置

时间:2014-12-11 21:59:49

标签: javascript html domdocument

我使用Ajax下载HTML代码,然后解析它:

var req = new XMLHttpRequest();
//Request for the current URL (such as http://example.org or http://stackoverflow.com/questions/27433215/give-document-proper-url-or-location)
req.open("GET", window.location.href);
req.onload = function() {
   //Returns Document object with `about:blank` in URL
   var doc = document.implementation.createHTMLDocument();
   //Put the code from request to the Document (all relative URL's are now lost)
   doc.documentElement.innerHTML = this.responseText;
   window.loadedDoc = doc;
}
req.send();

问题是文档的网址是about:blank。这会导致任何相对URL导致错误的路径。最重要的是,从href选择<a>会为您提供/path/而不是http://example.com/path/

我可以在某个时候设置正确的Document.URL吗?该网址应与当前window.location相同 - 因此不存在安全风险!

如果浏览器实现没有关于这种情况,是否至少可以正确替换链接URL?

1 个答案:

答案 0 :(得分:0)

尝试嗅探about:blank字符串,如果存在则不使用相对路径:

var url = window.location.href;

if (url == 'about:blank')
{
    // Use absolute paths
}
else
{
    // Use relative paths, as before
}

可能使用String.indexOf()

执行可能更可靠的执行比较的方法
if (url.indexOf('about:blank') !== false)
{
    // Use absolute paths
}