0

I have some code that in short, is opening an iframe (let's call it iframe1) to view a pdf file, and that pdf is being shown in an iframe itself (let's call it iframe2), I would like to be able to get the source of the iframe2 that is within an iframe1 that would be opened so that the iframe1 itself is just the src of the pdf iframe2 and not 2 different iframes. The Url's are very different.

what is the best way to do this?

I have an open_iframe function that looks something like

function open_iframe(url) {
    return '<iframe id="iframe" src="' + url + '" width=100% height=100% frameborder="0" allowfullscreen></iframe>';
}

and I am writing another function that is

function find_file_url(url) {
    let iframe = this.open_iframe(url);
    return iframe.contentWindow.document.getElementsByTagName('iframe')[0].src;
}

I also have Jquery available to use as well.

Is this something that's possible?

Is there a better approach?

Thanks in advance!

ghgg
  • 106
  • 3
  • 1
    Are they all in the same domain as the main page? There's no access to the contents of an iframe in a different domain. – Barmar Apr 01 '22 at 15:53
  • yes they are all on the same domain – ghgg Apr 01 '22 at 16:03
  • @Barmar for a little more context, the first URL will be something like example.com/show/1000 and the file itself that is showing within an iframe on that show page will be something like example.com/file/2938 – ghgg Apr 01 '22 at 16:15
  • `open_iframe()` doesn't return a DOM element, it just returns a string of HTML. You need to append the string to the DOM to create an actual iframe. And this will load the URL asynchronously, so you need to listen for the `load` event before trying to access the contents. – Barmar Apr 01 '22 at 16:18

2 Answers2

0

have you attached the iframe object to your dom? In this the html tag for "iframe" instead of creating a html string , you can create the dom iframe object directly and assign attributes to them and then parse it further. As Barmar said until then it would considered as just a html string. .document.getElementsByTagName('iframe') will be a null element as it is not attached to document object.

-1

You might try document.domain = "site.com" , I'm dealing with similar issue. This will ensure they are in the same domain

Also you can use iframe.contentWindow and iframe.contentDocument scripting to communicate inside for the nested frame.

also assign onload, errorOnload to the attributes for console tracking

iFrame onload JavaScript event

https://javascript.info/cross-window-communication

koralarts
  • 2,062
  • 4
  • 30
  • 48
TiLama
  • 1
  • Thank you figured this out, sorry for the long delay though . This about what we ended up doing to solver this – TiLama Jul 27 '22 at 00:23