1

I'm completely confused how to inject an entire html to another html using content scripts in chrome extension.

I'm currently doing

document.body.innerHTML += 'html';

But that only helps when injecting some minor html code, and not an entire html file, which has its own css and js files.

How do I achieve this?

4
  • General solution: use iframes. NEVER use document.body.innerHTML += '..';, because it will break almost every dynamic site on the internet... Commented Nov 29, 2013 at 21:15
  • @RobW When I saw the code used by Pocket, it was injecting code into the html div, rather than an iFrame. Commented Nov 29, 2013 at 21:25
  • @RobW I am taking the Pocket example, as that is something that I want to achieve and a bit more. Commented Nov 29, 2013 at 21:26
  • .innerHTML += will remove all event listeners and invalidate any previous element references. It should only be used on content you "own". <body> elements in arbitrary web pages do certainly not meet that criterium. Commented Nov 29, 2013 at 21:28

2 Answers 2

1

If you have been trying something similar to loading one html file into another, then the JQuery load() method might help:

$( "#mydiv" ).load( "thepageIwannaload.html" );

You can simply create the html you want to load as a separate html file and load it into your file.

Sign up to request clarification or add additional context in comments.

Comments

0

If I understand correctly, have you tried some ajax? something along the lines of...

var xmlRequestObject;
if (window.XMLHttpRequest)
{
xmlRequestObject=new XMLHttpRequest();
}

xmlRequestObject.onreadystatechange=function()
{
if (xmlRequestObject.readyState==4 && xmlRequestObject.status==200)
{
document.getElementById("elementID").innerHTML=xmlRequestObject.responseText;
}
}

xmlRequestObject.open("GET","document.html",true);

xmlRequestObject.send();

this ajax would work for the main browsers and substitute the arguements for the correct ones obviously. Hope I understood your question correctly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.