Javascript – Running a bookmarklet on an iFrame that is coming from a different domain

bookmarkletiframejavascriptSecurity

Is there any way to run a bookmarklet on an iFrame which is from a different domain?

For example, I have a page loaded from http://example.com, which has an iFrame whose source is set to http://example2.com. When I run the bookmarklet, it is always run on http://example.com, since that is the main page. I want to run it on the other iFrame though.

When I attempt to interact with the iFrame (e.g. by changing its source attribute to javascript:alert('test')), Chrome shows the following error:

Unsafe JavaScript attempt to access frame with URL http://example.com from frame with URL http://example2.com. Domains, protocols and ports must match.

I tried dragging and dropping the bookmarklet into the frame, but it says:

Failed to load resource

Is there any way for me to interact with an iFrame using a bookmarklet in Chrome?

Best Answer

There is a way to do cross-domain message-passing (not arbitrary code execution) using window.postMessage, yet all a frame A can do to frame B (when they are not of the same origin) is passing it a message hoping that B has a callback function listening for this message.

So here if you control exemple2.com (what's in the frame that don't get the bookmarklet), you can make the bookmarklet pass a message to the iframe and handle it in the iframe.

Else I don't think you have a solution here, except very complicated ones (like proxying).

Other links: