Carmageddon
Carmageddon

Reputation: 2829

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!

Upvotes: 2

Views: 1916

Answers (3)

Scimonster
Scimonster

Reputation: 33409

$.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 htmls in a row. :P

Upvotes: 0

chris vdp
chris vdp

Reputation: 2842

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/

Upvotes: 0

rockerest
rockerest

Reputation: 10508

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()

Upvotes: 2

Related Questions