简体   繁体   中英

Can i use postMessage on an iframe, who's html is passed via - srcdoc attribute?

I am unable to call postMessage in case, I pass html in the srcdoc attribute

without sandbox = "allow-scripts" , it give following error

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://example.com') does not match the recipient window's origin ('https://example.com:444').


with sandbox = "allow-scripts" , it give following error

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://example.com') does not match the recipient window's origin ('null').


I would like to call postMessage without the sandbox attribute, can I?

if not, is there any other way?

Sure you can.

The problem your error messages are complaining about is that you did set the target-origin parameter of Window.postMessage( message, target-origin, transferable ) to an invalid value.
You didn't show your code, but if I had to make a guess, I'd say you didn't set it at all and thus it did default to your current page's origin.

Since your target frame doesn't have an src but an srcdoc attribute, its location will be about:srcdoc and its origin will be null , so any other value than "*" for postMessage's target-origin will make the request fail.
You must set it to "*" .

 frame.onload = (e) => { frame.contentWindow.postMessage( 'hello frame', '*' ); };
 <iframe id="frame" srcdoc=" <html> <body> <pre id='log'></pre> <script> const log = document.getElementById( 'log' ); onmessage = (e) => log.textContent = e.data; </script> </body> </html> "></iframe>

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