Replacing HTML within an iframe jquery

夙愿已清 提交于 2020-01-06 07:43:25

问题


I have an iframed page and I'm trying to replace the only <p> within the iframe so that it links to a specific url

Here's my code:

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

What am I doing wrong? A note: I'm working within a CMS, however I do have access to the head and body tags, and I'm able to add scripts where I please.


回答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.



来源:https://stackoverflow.com/questions/34272167/replacing-html-within-an-iframe-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!