Farok Ojil
Farok Ojil

Reputation: 654

Replace Iframe with Ajax

My project is to have preview of some websites inside my website, I'm using Iframe for now to load the website preview and then the user can interact within the Iframe.

I have to change the Iframe implementation to be within the page For SEO purpose, So what could be the replacement is Jquery .load() function.

$('div#websitePreview').load('Website_URL');

but the problem is when the user interact with the website (click some link) the whole page will redirect to the new link, so is there a way to load the page which been clicked by the user in the same div by ajax call without leaving my website?

UPDATE: The websites I'm going to preview have subdomains of my original site

Upvotes: 3

Views: 2978

Answers (3)

Martin Lantzsch
Martin Lantzsch

Reputation: 1901

There is no way to achieve this, due cross domain security restrictions in modern browsers. You aren't allowed to access other domains content via ajax.

The other point is, that you may have css bugs if you load an entry page in a div on your site, because the loaded css will override your site's css.

Upvotes: 3

Rory McCrossan
Rory McCrossan

Reputation: 337560

Assuming the websites you are 'previewing' are on the same domain as your website, you can amend every a tag within the loaded div to perform an AJAX request with the following code:

var $container = $('#websitePreview')
$container.load('http://www.example.com'); // initial load

// link click within loaded content.
$container.on('click', 'a', function(e) {
    e.preventDefault();
    $container.load($(this).attr('href'));
});

On the other hand, if the previewed sites are on separate domains, you cannot load HTML from them due to the Same Origin Policy. An iframe or CORS request is your only option in those situations, and if the url is 3rd party, the latter is extremely unlikely to happen.

Upvotes: 1

jackchuka
jackchuka

Reputation: 72

try

$('div#websitePreview a').live('click', function(event){
   event.preventDefault();
   var url = $(this).attr('href');
   $('div#websitePreview').load(url);
}

Upvotes: 0

Related Questions