Anthony Carbon
Anthony Carbon

Reputation: 618

Load the page inside of IFRAME using ajax

how about loading your page using IFRAME ? I was thinking if this is possible ..

Example, i have this iframe below.

<iframe id="iframe" width="1024" height="600" src="http://www.sample.com"></iframe>

I want the www.sample.com page to load inside this iframe by not simply add the URL into src attribute, instead I'll get the current page data using ajax and to load using IFRAME tag. I'm thinking about this because I have a big problem on IFRAME cache most of the time.

I also try this thing but, it does not work perfectly on my end.

<iframe id="iframe" width="1024" height="600" src="http://www.sample.com?random=1422841682605""></iframe>

random is change everytime i load this iframe.

I want to apply it on my responsive tool like on the image below. If you need an actual view click here.

enter image description here

Thanks guys if have some idea out there .

Upvotes: 9

Views: 34523

Answers (4)

DRAB
DRAB

Reputation: 445

You can change the location of an iframe with Javascript with a few different methods.

var frame = document.getElementById("iframe");
frame.src = "http://www.sample.com";
frame.contentWindow.location = "http://www.sample.com";
frame.contentWindow.open("http://www.sample.com");

Of course, you must be very careful with iframes. If the iframe points to a foreign domain (ie: "Cross-Origin", ie: NOT the same domain on which the main web page is hosted) you will breach browser security policies and will throw errors if you try to manipulate / read many properties.

Also note that by changing an iframe element's src attribute, the iframe will automatically travel to the new location. However, if you use one of the other two methods I suggested, the src attribute of the iframe element will not change (even though the iframe's content points to a new location).

If you need to get the location of an iframe, you can try:

iframe.contentWindow.location.href;

Again, however, if the iframe is pointing to a site that is not hosted on the same domain, this will cause an error. To be safe, use try {} catch (e) {} blocks.

Upvotes: 3

c-smile
c-smile

Reputation: 27460

You can still use src but supply data URL like this:

src = 'data:text/html;charset=utf-8,' + 
    encodeURIComponent( // Escape for URL formatting
        '<!DOCTYPE html>'+
        '<html lang="en">'+
        '<body><h1>Another document!</h1></body>'+
        '</html>'
    );

Upvotes: 6

sideroxylon
sideroxylon

Reputation: 4416

If www.sample.com is on the same domain, you can just do this:

<div id = "targetDiv"></div>
<script>
$('document').ready(function() {
    $('#targetDiv').load('www.sample.com');
});
</script>

Though, if it is the same domain, you'd probably use .load('/');

Upvotes: 1

Mustafa
Mustafa

Reputation: 13

Make sure to use "http://" before the link, example:

<iframe src="http://www.google.com"></iframe>

Upvotes: 1

Related Questions