Skip to content Skip to sidebar Skip to footer

Replacing Html Within An Iframe Jquery

I have an iframed page and I'm trying to replace the only

within the iframe so that it links to a specific url Here's my code: $('#custom-iframe').contents().find('p').re

Solution 1:

Here is the issue: You loaded some url in an iframe. <iframe src="http://someurl.com"></iframe> But loading url takes some time, browser has to send request and receive response and display the response in the iframe element. But javascript does not wait for the response, it attaches a listener to the load event of the request and moves to execute the next line. So when your code is getting executed, the iframe element might be empty because the response for the iframe src url has not arrived. The correct way to handle this is:

$("#custom-iframe").on('load',function()
{
  $(this).contents().find("p").replaceWith("<p><a href='http://www.myurl.com'>blah blah blah.</a></p>");

});

Theoretically this should work because when load event fires then loading of url has been completed and all the elements of the external page is available. But one more thing to keep in mind is : For security reasons browsers does not allow modifying an external page loaded in an iframe when protocol and domain of the parent pageurl and iframe pageurl differ.

You might see this kind of error in console: Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://localhost:63342" from accessing a frame with origin "http://someurl.com". Protocols, domains, and ports must match.

Post a Comment for "Replacing Html Within An Iframe Jquery"