Crashalot
Crashalot

Reputation: 34513

jQuery + SVG: unable to access SVG element in iFrame

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);
          });

    });

Upvotes: 0

Views: 320

Answers (2)

ylerjen
ylerjen

Reputation: 4249

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)

Upvotes: 1

TechieViking
TechieViking

Reputation: 136

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

Upvotes: 2

Related Questions