Send a message from an iframe on the main page - javascript

I have seen from this documentation: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage , the way to pass a data correctly to an iframe. But now I want to send an answer:
//from main page
myIframe.contentWindow.postMessage('send me a response', '*');
//from iframe of main page
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event){
alert(event.data);//the value of message
//now i need to send an answer 'this is a response'
}
}
How do I send an answer to the main page from the iframe?
I need really of this answer.
Edit:
Ok i found the solution ty at all.

You have access to the parent window on the global window.parent.
I believe it is as easy as using this object's method at this point to postMessage. So something like:
var parent = window.parent;
parent.postMessage("some message");
A full example can be found here.
The gist is the window.parent.postMessage() function takes the following arguments: otherWindow.postMessage(message, targetOrigin, [transfer]);

I would consider using easyXDM
EasyXDM WebSite

Related

Using postMessage to extension background page

I'm trying to send a CryptoKey (generated by SubtleCrypto.generateKey()) object from a contentscript to the background page of a webextension.
When using chrome.runtime.sendMessage to send the object, it is lost, as CryptoKey is not stringifyable (see also this question). Using window.postMessage to transfer the key to another window does work, as this method uses structured cloning..
Is there something similar to postMessage to send data that is not stringifyable to the background page of a webextension?
Thanks to the comment by #wOxxOm I solved it by creating a web accessible resource with this code:
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
chrome.extension.getBackgroundPage().postMessage(event.data, "*");
}
This is triggered by the contentscript like that:
let iframe = document.createElement('iframe');
iframe.setAttribute('src', chrome.extension.getURL('webaccessible/index.html'));
iframe.addEventListener("load", () => {
iframe.contentWindow.postMessage(data);
})
While data is an object that contains the CryptoKey.
This data is received in the background script just like you normally would receive such messages:
window.addEventListener('message',(event) => {
console.log(event);
});

How to postmessage HTMLIFrameElement?

I'm having issue passing HTMLIFrameElement object from parent site to iframe (located on a different domain) using postMessage method.
This is my code that I already tried:
var frame = document.getElementById('myHTMLIFrameElement');
frame = JSON.parse(JSON.stringify(frame));
event.source.postMessage(frame, "*");
Unfortunately, JSON.parse/JSON.stringify does not seem to be the right way of handling HTMLIFrameElement object. Can you please advise how to pass through HTMLIFrameElement object correctly?
Parsing DOM elements as JSON does not do anything useful as far as I know.
Since postMessage() is part of the window object, you could try using the window object of the frame, which is found under the contentWindow property of the iframe.
So you could try something like:
var frame = document.getElementById('myHTMLIFrameElement');
frame.contentWindow.postMessage( "stuffYouWantToSendToTheIframe", '*' );
And then in the script inside the iframe:
window.addEventListener('message', function( event ) {
// handle message
});

Send JavaScript to an iFrame that uses a different port?

I have been having some issues sending JavaScript to an iFrame that uses a different port and after searching online it seems that the 'different port' part is causing the issue.
Here is the code sending JavaScript to the iFrame:
<script>
var network = document.getElementById("1").contentWindow.kiwi.components.Network();
$(".irc-channel-selector").click(function(event){
network.join('#' + $(this).attr('data-irc-channel'));
});
</script>
The iFrame does not use port 80 which appears to be the problem:
<iframe id="1" src="http://www.example.com:7888">
I understand that I can use something called postMessage to do the same as what I need but having read up on it online I'm not sure how it should be used, it seems pretty complex whereas I'm only used to basic JavaScript such as the code that I wrote above.
Can someone provide an example on how I can use this postMessage to mimic the behaviour above? Reading online documentation I do not understand how to use it in my scenario! :(
It's not very complicated to achieve this with postMessage. First, inside the iframe, you must expect a message:
var network = kiwi.components.Network();
function receive(event) {
// it is important to check the origin. Here I'm assuming that the parent window has that origin (same address, default port).
// if you don't check the origin any other site could include your iframe and send messages to it
if (event.origin === "http://www.example.com") {
var message = event.data;
// Assuming you might want different message types in the future. Otherwise message could be just the channel itself.
if (message.type === "JOIN") {
network.join(message.channel);
}
}
}
window.addEventListener("message", receive, false);
Now your iframe page is expecting a message to make it join a channel. The parent page can send that message with:
$(".irc-channel-selector").click(function(event){
var message = {
type: "JOIN",
channel: '#' + $(this).attr('data-irc-channel')
};
// Notice that again we're using the specific origin you used in your iframe
document.getElementById("1").contentWindow.postMessage(message, "http://www.example.com:7888");
});
Here's a far more simple fiddle where a message is sent to the same window, since I'd have to host a page somewhere to have an iframe in jsfiddle: https://jsfiddle.net/3h1Lw0j4/1/ -- Anyway it's useful to see how event.origin behaves.

postMessage() generates error "undefined is not a function"

I'm trying to get postMessage() to work to communicate between an iframe and my main website. However using the exact syntax given in the example code on MDN, I am being presented with a nice Undefined is not a function error. I've tried several things, such as initializing the iframe inside Javascript and appending it to my page, but that left me with the same error. Same for have seperate selectors to select my iframe.
I have the following Javascript code:
<script type="text/javascript">
$(document).ready(function() {
$('.editor').postMessage("A", "domain here");
});
function receiveMessage(event)
{
if (event.origin !== "domain here")
return;
// Do something
}
window.addEventListener("message", receiveMessage, false);
</script>
The script above tries to send a message to my iframe on the page, which looks like:
<iframe src="domain here/frameListener.html" class="editor"></iframe>
It then has a function receiveMessage to catch any messages being send as a response to the main webpage. Last but not least, I've tried the answers given in this question: But that did not fix my problem. It is therefore not a duplicate.
How can I get rid of this error message?
postMessage is not a jQuery function so you need to get the actual window DOM element and call it on that:
$('.editor').get(0).contentWindow.postMessage("A", "domain here");
Furthermore, you need to access the contentWindow property of the iframe. Here is an excerpt from the MDN docs:
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow
A reference to another window; such a reference may be
obtained, for example, using the contentWindow property of an iframe
element, the object returned by window.open, or by named or numeric
index on window.frames.

Functions() out of iframe? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
Is it possible to call Javascript function in parent document from JS in iframe?
I have a main.php page.
This contains an iframe which src is random.php.
How can I have script in the main.php with a random function, random(), and let random.php use that function?
If you are working with HTML5, you can use the postMessage() function..
here is a nice demo:
http://html5demos.com/postmessage
UPDATE
The idea is to postMessage to the iframe window object, each window is listening to the message event like so:
In your main.php:
window.addEventListener("message", function(e){
var data = e.data; // data can be any object for example { type: 'random', payload: {}... }
switch(data.type){
case 'random':
// do somthing here with the payload...
break;
}
});
in your iframe (random.php):
window.parent.postMessage({ type: 'random', payload: {...} });
You can call the function random in the page that contains the iframe using window.parent.random(). If you want to do the opposite, namely calling a function in an (i)frame from a containing page, you should use [DOM Reference to frame].contentWindow.random() instead.
↪ More information about window.parent at the Mozilla Developer wiki
If random.php is at a different domain, you can't do this because of the Same Origin Policy. If that's the case, you can use HTML5 postMessage to transfer information across pages*. This does not allow you to directly call functions of a different domain's JavaScript, however.
* See Can I use for browser support information

Categories

Resources