简体   繁体   中英

jQuery: How to replace the whole DOM with another HTML using .load

I have a problem. We are doing a Captive Portal.

Go to any site, for example www.php.net Then in Chrome's console, use this:

$("html").load( "https://www.ccc.co.il/Suspend.aspx" );

You will notice, the DOM is replaced, but not quite the way it should be: The wrapper elements of the loaded webpage (title, body for example) are missing!

This causes problems of course on the injected page.

How do I replace the entire initial DOM? And please dont suggest to me using a link, or normal redirect. Those are the restrictions, I need to replace the entire DOM tree please.

Thanks!

This is fundamentally a feature of browsers.

Here's a snip from the jQuery docs for .load() :

jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as <html> , <title> , or <head> elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.

While I don't recommend what you're suggesting at all, I will attempt to answer your question:

Using a server-side language (like PHP, for example), return documents as parsed json:

{
    "head": [head string],
    "body": [body string]
}

Then your JavaScript can individually replace each element. You'll need to switch from .load() to something more configurable, like .ajax()

I think you would have to use an iframe in this case as I don't think that you can replace an entire DOM with another.

$('body').html("<iframe height=100% width=100% frameBorder=0 src='https://www.ccc.co.il/Suspend.aspx'></iframe>");

http://jsfiddle.net/c7EbY/

$.get("https://www.ccc.co.il/Suspend.aspx", function(html){$("html").html(html)});

I'm using a regular AJAX function here because it shouldn't strip anything.

Sorry about those 4 html s in a row. :P

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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