Search code examples
javascriptiframeclosuresmicrosoft-edge

Can I call a function in iframe, if it's inside a closure?


I have this crazy idea of:

  • Embedding fast.com in an iframe on my own website
  • Triggering it by restartTest() or click on div#speed-progress-indicator-icon

enter image description here

I know that I can trigger any method, event or function in embed iframe:

document.getElementById('targetFrame').contentWindow.targetFunction();

But then it seems that I can't trigger it, because it is inside a closure.

On "master" side (no embed) it goes like this:

var o = document.getElementById('speed-progress-indicator-icon');
o.click();

Will it work in the iframe as well?

I am asking (instead of trying myself), because I can't do any tests myself from where I am writing right now, sorry -- can't modify or save any files. Can only run console commands on read-only accessed files.

And the thing that makes me suspicious that I am doing this all wrong (and thus that it certainly won't work in an iframe) is that am I getting this error after o.click()?

app-a32983.js:3 
    
   Uncaught TypeError: Cannot read properties of null (reading 'className')
at hasClass (app-a32983.js:3:24556)
at HTMLDocument.<anonymous> (app-a32983.js:3:27092)
at <anonymous>:1:3

Can anyone advice on what am I missing here?

(Edge 110, Windows 11 Pro)


Solution

  • Will it work in the iframe as well?

    No, it won't work if you put it in an iframe (also tested here). Script access to a frame's content is subject to the same-origin policy. In this case, it is obvious that it does not conform to the same-origin policy.

    For more information of iframe (same-origin policy), you can read this doc.