简体   繁体   English

在跨源AJAX调用中解析相对URL?

[英]Parse relative URLs in cross-origin AJAX call?

I am writing a Chrome extension. 我正在写一个Chrome扩展程序。 I want to make an AJAX request to a remote URL, parse the return data as HTML and then interact with the DOM, like click links: 我想向远程URL发出AJAX请求,将返回数据解析为HTML,然后与DOM交互,例如单击链接:

$.ajax({
    url: remote_url,
    success: function(data) {
        $(data).find('some element').click()
    }
})

The problem is that relative URLs ( /x/y/ ) on the page referred to by remote_url are being parsed as part of the chrome extension's address space when creating a new DOM with $(data) , like chrome-extension://abc/x/y/ . 问题是,使用$(data)创建新的DOM时,由remote_url引用的页面上的相对URL( /x/y/ )被解析为chrome扩展的地址空间的一部分,例如chrome-extension://abc/x/y/

I suspect that this is related to some cross-origin protection. 我怀疑这与某些跨域保护有关。 Is there any way to get around this? 有什么办法可以解决这个问题?

Resolve the relative links using HTML5 URL class: 使用HTML5 URL类解析相对链接:

$data = $(data);
$data.find('[href]').each(function() {
    var href = this.getAttribute('href'); # 'this' is a DOM element
    if (href.indexOf('://') < 0) {
        this.href = new URL(href, remote_url);
    }
});

Or use HTML5 DOMParser with base element to resolve all relative links, not just in href . 或者将HTML5 DOMParser基本元素一起使用来解析所有相对链接,而不仅仅是在href

  • data contains a fragment without html/body: data包含不带html / body的片段:

     var $doc = $(new DOMParser().parseFromString('<html><head><base href="' + remote_url + '"></head><body>' + data + '</body></html>', 'text/html')); 
  • data contains entire page: data包含整个页面:

     var $doc = $(new DOMParser().parseFromString(data, 'text/html')); $('head', $doc).append('<base href="' + remote_url + '">'); 

$doc.find('some element').click();

If you are receiving that URL as a string I would just parse it up with some regular old Javascript and remove the parts you don't want. 如果您以字符串形式接收该URL,则只需使用一些常规的旧Javascript对其进行解析,然后删除不需要的部分。 If you want some more help, just post the full string you're receiving and the string that you need and I can take a look. 如果您需要更多帮助,只需张贴您收到的完整字符串和所需的字符串,我可以看看。 You'll probably just end up using a .split().pop().join() kind of a thing, but I'd love to take a look and give you a definitive answer. 您可能最终只会使用.split()。pop()。join()之类的东西,但是我很乐意看一下并给您明确的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM