Jeach
Jeach

Reputation: 9052

Rewriting domain (or IP address) within an HTML file using jQuery

I'm currently using jQuery to load() a third-party HTML file for which I inject it into a DIV of our current HTML page.

$("#external-page").load(URL, function() {
   injectDataInPage();
   doOtherStuffInPage();
});

This works very well. The major problem is that they have added a lot of code in their HTML (ie: buttons which issue server requests and resources loaded from another server, etc).

If they have used paths only for their requests then it would be ok but unfortunately, they specify the domain and sometimes an IP address.

I would like to replace ALL of the hard-coded domain and IP addresses to point to my own server.

So for example, these:

<a href='http://external.com/some/path/of/service'>Click here</a>

<img src='http://10.2.3.4/some/path/to/image.png'>

Would be remapped to:

<a href='http://my.domain.com/some/path/of/service'>Click here</a>

<img src='http://my.domain.com/some/path/to/image.png'>

I know you can probably do it with IIS plugins or a Node.js or something but is it possible to actually do it on the client with jQuery? Either once the page has been added to the DOM or possibly before injecting it to the DIV.

Upvotes: 0

Views: 197

Answers (2)

Tieson T.
Tieson T.

Reputation: 21231

You may also find something like URI.js useful. For instance, you could use a replace function with their resource() function to make all the URLs relative.

For example:

$("#external-page").load(URL, function() {
    injectDataInPage();

    $("#external-page img").each(function(i, img){
        var src = $(img).attr('src');
        $(img).attr('src', new URI(src).resource());
    }); 

    $("#external-page a:link").each(function(i, link){
        var href = $(link).attr('href');
        $(link).attr('href', new URI(href).resource());
    }); 

    doOtherStuffInPage();
});

Granted, this is untested, but the idea should be obvious.

Upvotes: 1

shukshin.ivan
shukshin.ivan

Reputation: 11340

Insert it after loading done.

$('a[href]').each(function(){
    $(this).attr('href', $(this).attr('href').replace("http://external.com", "http://my.domain.com");
});

$('img[src]').each(function(){
    $(this).attr('src', $(this).attr('src').replace("http://10.2.3.4", "http://my.domain.com");
});

You can prepend 'a[href]' with some div selector: '.mydiv a[href]' to prevent watching all the elements.

Upvotes: 1

Related Questions