Skip to content Skip to sidebar Skip to footer

Injecting HTML Into Existing Web Pages

I'm interested in the concept of injecting a bit of HTML into existing web pages to perform a service. The idea is to create an improved bookmarking system - but I digress, the spe

Solution 1:

Yes, you can absolutely do this. You're asking about Bookmarklets.

A bookmarklet is just a bookmark where the URL is a piece of JavaScript instead of a URL. They are very simple, yet can be capable of doing anything to a web page. Full JavaScript access.

A bookmarklet can be engaged on any web page -- the user simply has to click the bookmark(let) to launch it on the current page.

Bookmark    = "http://chasemoskal.com/"
Bookmarklet = "javascript:(function(){ alert('I can do anything!') })();"

That's all it is. You can create a bookmarklet link which can be clicked-and-dragged onto a bookmark bar like this:

<a href="javascript:(function(){ alert('anything is possible') })();">Bookmarklet</a>

Bookmarklets can be limited in size, however, you can load an entire external script from the bookmarklet.


Solution 2:

You can do what you refer to as like an <iframe>, so here are some steps that may help you, simply put:

  1. Create an XMLHttpRequest object and make a request for a page trough it.
  2. Make the innerHTML field of an element to hold the resultString of the previous request, aka the HTML structure.

Lets assume you have an element with the id="Result" on your html. The request goes like this:

var req = new XMLHttpRequest();
req.open('GET', 'http://example.com/mydocument.html', true);
req.onreadystatechange = function (aEvt) {
    if (req.readyState == 4 && req.status == 200) {
        Result.innerHTML = req.responseText;
    }
};
req.send(null);

Here's an improved version in the form of a fiddle.

When you're done, you can delete that injected HTML by simply:

Result.innerHTML = '';

And then anything inside it will be gone.

However, you can't make request to other servers due to request policies. They have to be under the same domain or server. Take a look at this: Using XMLHttpRequest on MDN reference pages for more information.


Post a Comment for "Injecting HTML Into Existing Web Pages"