简体   繁体   中英

Import entire HTML page into another page

I'm trying to embed another website within my website but I don't want to do it with an iFrame or AJAX import due to some issues that would cause.

 <html> <head> <link rel="import" href="mysite.html"> </head> <body> <script> var link = document.querySelector('link[rel="import"]'); var content = link.import; document.body.appendChild(content.cloneNode(true)); </script> </body> </html> 

Basically I'm trying to do this with HTML Imports from Web Components but unfortunately what I have above does not work (I am using the right browser too) and all the examples I've found were only for importing a specific div or element from within an imported page. But is it possible to simply load the entire page and embed it in another site?

It doesn't work because the object you get from the import property of the <link rel="import"> element is a Document interface. You cannot insert this type of object inside a <body> element.

Instead you should at least get the <html> element of the imported document from its documentElement property:

 var content = link.import.documentElement  //returns a html element

But it still incorrect because you will then insert a <html> element inside a <body> element, which is ugly.

You'd rather copy the innerHTML text of the imported document to the main one:

 document.body.innerHTML = link.import.querySelector( 'body' ).innerHTML

Or put the HTML you want to import inside a <template> , which is better if you want to defer scripts execution and loadings.

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