2

Is there a way to programmatically select frame context with Javascript? Let's say there are two different frames present in the current web page, and I need to append 'hello' to the second frame. The problem is that the second frame has a different domain than the current web page. With chrome developer tools, I can simply choose the second frame context and do $('body').append('hello') from console, but I should be able to do this programatically.

Reference: Debugging iframes with Chrome developer tools

Is there a way to achieve this?

intention: I need to create a bookmarklet that specifically targets the frame that has a different domain than the main webpage.

Community
  • 1
  • 1
Maximus S
  • 10,759
  • 19
  • 75
  • 154
  • related [frame access not possible from dev tools console due to cross-origin restrictions](https://stackoverflow.com/questions/64857289/). – surfmuggle Nov 28 '21 at 19:12

1 Answers1

0

Same domain is easy:

 window.parent.doSomeThing()

Cross origin is a little tricky

window.postMessage allows for sending data messages between two windows/frames across domains

Caniuse.com lists the browsers already supporting cross-document (postMessage).

surfmuggle
  • 5,527
  • 7
  • 48
  • 77
VDP
  • 6,340
  • 4
  • 31
  • 53
  • Hi @VDP. Thanks for your help. I am trying to use postMessage, but doing `otherWindow.addEventListener("message", receiveMessage, false);` results in security error because of cross origin. This defies the purpose of using postMessage API in the first place because that's precisely what I need. Do you have any advice? – Maximus S Mar 19 '14 at 16:17
  • My bet is you're using IE < IE11 :( It seems it's a [known issue](http://caniuse.com/#feat=x-doc-messaging)... Here's another stackoverflow [question](http://stackoverflow.com/questions/16226924/is-cross-origin-postmessage-broken-in-ie10) about it. – VDP Mar 20 '14 at 07:56