Friday, May 15, 2015

iFrame content via JQuery

We can access the content of iFrame using JQuery using $("#iframe1").contents().find("html").html(), however it works only if iframe belongs to the same domain as parent container.

E.g. for below HTML, iframe1 and iframe3 is pointing to external URL and iframe2 is pointing the page with same domain:

1:  <html>  
2:       <head>  
3:            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"></script>  
4:       </head>  
5:       <body>  
6:            <button type="button" id="iframecontent" onclick="iframecontent_click()">IFrame Content</button>  
7:            <iframe id='iframe1' frameborder="0" height="300pt" scrolling="auto" src="http://testserver.com?func=ll&amp;objId=92043&amp;objAction=browse&amp;saptheme=default&amp;wanttabs=0" style="background-color: transparent; border: 0px none transparent;padding: 0px" width="100%"></iframe>  
8:            <iframe id='iframe2' frameborder="0" height="300pt" scrolling="auto" src="test2.html" style="background-color: transparent; border: 0px none transparent;padding: 0px" width="100%"></iframe>      
9:            <iframe id='iframe3' frameborder="0" height="300pt" scrolling="auto" src="http://www.cnn.com" style="background-color: transparent; border: 0px none transparent;padding: 0px" width="100%"></iframe>      
10:       </body>  
11:       <script>  
12:            function iframecontent_click() {  
13:                 console.log('iframe1 content : ' + $("#iframe1").contents().find("html").html());  
14:                 console.log('iframe2 content : ' + $("#iframe2").contents().find("html").html());  
15:                 console.log('iframe3 content : ' + $("#iframe3").contents().find("html").html());  
16:            }  
17:       </script>  
18:  </html>  

Here via Jquery iframe1 and iframe3 content shows up as "undefined". It works fine for iFrame2.


In SalesForce, if you include visual force page inside the standard page, it is included inside the iFrame and Salesforce includes visual force page with different domain iFrame, as below. Hence in parent container JQuery would not be able to access content of child visual force page iframe.



No comments: