简体   繁体   中英

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

    });

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM