0

Questions like this and this say using jQuery contents() lets you access an iFrame element.

However, this code isn't working.

It isn't an cross-origin issue as both parent and iFrame are hosted on the Codepen.io domain.

If you view the Codepen, you can see the iFrame has a child SVG element called designBox.

$(document).ready(function() {

          $("#livePreview").on("load", function() {
             var designBox = $("#livePreview").contents().find("#designBox");
             var livePreviewContents = $("#livePreview").contents();

             console.log("Loaded live preview. Design box: " + designBox.length + ". Live preview contents: " + livePreviewContents);
          });

    });
Crashalot
  • 33,605
  • 61
  • 269
  • 439

2 Answers2

2

You may be facing same origin policy issue. You can't access the contents of an iframe with different origin using JavaScript, it would be a huge security flaw if you could do it. For the same-origin policy browsers block scripts trying to access a frame with a different origin.

I am sharing a link where it is explained in detail to access the content of an iframe and various scenarios Follow this link

TechieViking
  • 126
  • 1
  • 10
1

If you take a look at your developer tools, you'll notice there is a middle iFrame with id result that is added by Codepen. This because the iframe you add is a codepen page that also already contains an iframe.

The structure is like :

|--- iframe#livePreview -------|
| |--- iframe#result --------| |
| | |--- svg#designBox ----| | |
| | |                      | | |
| | |______________________| | |
| |__________________________| |
|______________________________|

So you'll need to add another contents() call to go inside this iframe#result and then get your svg.

=> $("#livePreview").contents().find("#result").contents().find("#designBox"); But you probably will have to manage the load event of the nested iframe (I haven't tested it)

ylerjen
  • 4,109
  • 2
  • 25
  • 43
  • 1
    Unfortunately, codepen does execute `#result` frame on a subdomain, so this won't work, even though it was spot on too. – Kaiido Dec 29 '18 at 12:15