Javascript, postMessage to Iframe - javascript

<body onload="onload();">
function onload()
{
document.onkeypress = function(e) {
//e.preventDefault(); // Prevent any default browser behaviour.
console.log('send: '+e);
document.getElementById('iframe').contentWindow.postMessage ('Hello Treehouse!', '*my*');
}
window.addEventListener('message', function(event) { console.log('get: '+event); }, false);
}
</script>
I want to forward keypresses to iframe but so far it doesnt work, iframe doesnt receive the messages

It looks like you're trying to bind the event listening within the same window as the sender, when you actually need that within the iFrame itself.
i.e. within your iFrame have this code:
<script>
window.addEventListener('message', function(event) { console.log('get: '+event); }, false);
</script>

Related

window.addEventListener is listening to window.parent.postMessage twice

When certain button is being clicked from child Iframe this function is being fired:
function someFunc(e) {
some Code
window.parent.postMessage(
{
event_id: 'id_id',
data: {
note: note
}
},
"*"
);
}
In Parent Window it's being listened
window.addEventListener('message', function (event) {
if (event.data.event_id === 'id_id') {
var note = event.data.data.note;
do something with note
}
},false);
The problem here is for one click someFunc() function is being called once but somehow window.addEventListener listener is listening to it twice. Can't find why it's behaving in such way.
I had the same problem in my Angular 8 app.
The only way I got rid of these multiple messages between the listener and the iFrame was to add this code to my component:
ngOnDestroy() {
window.removeEventListener('message', this.messageHandler, false);
}
This leads to the conclusion that there are not multiple messages, but multiple listeners.

javascript postmessage doesn't work

i have 2 sites, and i want to use javascriptpostMessage between them.
on my main site i write the following code in an emty html file :
<html>
<script>
window.addEventListener("message",listener_,false);
function listener_(event) {
console.log('ok!');
<html>
<script>
window.addEventListener("message",listener_,false);
function listener_(event) {
console.log('ok!');
//console.log(event);
//console.log(event.data);
}
</script>
</html>
and in other site that i want to call the postmessage from the i write the following code:
<script type="text/javascript">
window.onload = function() {
testfunction();
};
function testfunction(){
var childWin = window.open("http://my-main-site.com/indexjava2.html","child");
childWin = postMessage('message','*');
console.log(TipaltiIframeInfo.height);
}
</script>
but it doesn't work after a lot of tries. i mean
console.log('ok!'); or console.log(event); console.log(event.data);
doesn't trigger on console of main site,
what to do?
thanks
Aside from the fact that you've got a <script> and an <html> tag in the middle of your code for the receiving page and you're defining and adding the event listener twice, you're also not use postMessage correctly. Instead of this:
childWin = postMessage('message', '*');
...it should be this:
childWin.postMessage('message', '*');
If you want to learn more about postMessage, read this.
The other issue is that the message won't be received by the newly-opened page unless the page is opened before the message is sent. You're trying to send the message immediately after opening the new page, and the message is reaching the new page before the event listener is added. You could get around this with a setTimeout, but if the new page takes longer to load then this might also be unreliable.
// This is what NOT to do:
setTimeout(function() {
childWin.postMessage('message', '*');
}, 1000);
Instead, the better way is for the child page to tell the parent page when it's loaded. Then the parent and child can communicate reliably.
Here is the full corrected code, sending page first:
<script>
var childWin;
window.addEventListener('message', messageListener, false);
function messageListener(event) {
if(event.data == 'ready') {
childWin.postMessage('hello second page', '*');
}
}
window.onload = function() {
childWin = window.open('http://my-main-site.com/indexjava2.htm', 'child');
};
</script>
And the receiving page:
<script>
window.addEventListener('message', messageListener, false);
function messageListener(event) {
console.log(event.data);
}
window.opener.postMessage('ready','*');
</script>

PhoneGap Back Button exit the Application

Currently i am working on Mobile Apps using PhoneGap (Cordova 2.2), JQuery and Javascript. Landing Page is Login Page. So once i entered into Dashboard Page using login credentials, when i click the BACK BUTTON its returns to the login page not stay on dashboard page. What can i do??? Suggestions welcome.
I've tried,
SCRIPT
<head>
<script type="text/javascript" charset="utf-8" src="cordova-2.2.0.js"></script>
<script type="text/javascript" charset="utf-8">
// Call onDeviceReady when Cordova is loaded.
//
// At this point, the document has loaded but cordova-2.2.0.js has not.
// When Cordova is loaded and talking with the native device,
// it will call the event `deviceready`.
//
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
// Cordova is loaded and it is now safe to call Cordova methods
//
function onDeviceReady() {
// Register the event listener
document.addEventListener("backbutton", onBackKeyDown, false);
}
// Handle the back button
//
function onBackKeyDown() {
alert("Back Button Clicked"); //called the alert..checking
}
</script>
HTML
<body onload="onLoad()">
</body>
My onDeviceReady and onBackKeyDown Function not working / Fired. Am i missing something???
Try with loggin variable to check if login and do something on the call back function.
function onBackKeyDown(evt) {
evt.preventDefault();
evt.stopPropagation();
if(loggedin=='yes'){
//dont do anything or show popup
}else{
history.back();
}
}
You need to bind the eventLinstener first, and call the app.initialize() in the page onLoad OR $(document).ready() method.
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
document.addEventListener("backbutton", onBackKeyDown, false);
}
};
Try this
//after successful login
localStorage.setItem('login', 1);
// and your back function callback
function onBackKeyDown(e) {
e.preventDefault();
e.stopPropagation();
var isLogin = localStorage.getItem('login);
if (isLogin){
// stay here
} else {
history.back();
}
}

window.addEventListener not being executed on click events

This is a very basic Firefox addon , it opens a new tab and loads the specified html file.
It attachs a ContentScript to the tab but for some reason alert('in event listener'); is never executed?
Although alert('in script'); does run.
Whys that?
main.js
var tabs = require("sdk/tabs");
tabs.open({
url: require('sdk/self').data.url('html/view.html'),
isPinned: true,
onOpen: function onOpen(tab) {
console.log("onOpen");
tab.attach({
contentScriptFile: require('sdk/self').data.url('js/controller.js')
});
}
});
controller.js
window.addEventListener('click', function(event) {
alert('in event listener');
}, false);
alert('in script');
alert(document.getElementById("text").value);
// output
// console.error: MyApp:
// Message: TypeError: document.getElementById(...) is null
view.html
<html>
<body>
<textarea id="text">yo</textarea>
</body>
</html>
moving to solution.
Change onOpen to onReady and instead of document.addEventListener use window.addEventListener. bobbyrne01 reports that it works, no clue why this fixed it though.

Call iframe function in parent window

How can i call iframe function in parent window, i did something like below but not seems working in firefox. Same code working perfectly in chrome.
window.frames["original_preview_iframe"].window.exportAndView(img_id);
i think you have to use
document.getElementById('target_Frame').contentWindow.callingtargetFunction();
otherwise use this url describes solution for your problem
Invoking JavaScript code in an iframe from the parent page
Try to not type window after you 'selected' the iframe:
window.frames["original_preview_iframe"].exportAndView(img_id);
Would suggest this https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
Clear wiki example that worked for me:
var o = document.getElementsByTagName('iframe')[0];
o.contentWindow.postMessage('Hello B', 'http://example.com/');
And then in the iframe:
function receiver(event) {
if (event.origin == 'http://example.net') {
if (event.data == 'Hello B') {
event.source.postMessage('Hello A, how are you?', event.origin);
}
else {
alert(event.data);
}
}
}
window.addEventListener('message', receiver, false);
(https://en.wikipedia.org/wiki/Web_Messaging.)
There are several ways to call the iframe function.
We assume you iframe id is original_preview_iframe
Way 1
You can use document.getElementById("original_preview_iframe").contentWindow.exportAndView() to trigger.
Way 2
Use window.frames.
window.frames is an array, you can set the iframe name with window.name="this is iframe test" in "test.html"
Then you can iterator the array, and compare the name, then trigger it.
for (let i = 0; i < window.frames.length; i++) {
if (window.frames[i].name === "this is iframe test") {
window.frames[i].exportAndView()
}
}
Way 3
Use postMessage.
In the way1 and way2, you need to assign function in the window object.
<body>
<script>
// this one
window.exportAndView = function(){}
// or this one
function exportAndView(){}
</script>
</body>
In the Way3, you can hide the exportAndView then you also can trigger it.
Here is an example.
// a.html
<html>
<body>
<iframe id="original_preview_iframe" src="/b.html">
</iframe>
<script>
// let postMessage trigger after b.html load
setTimeout(function(){
document.getElementById("original_preview_iframe").contentWindow.postMessage({data: "hi"});
}, 500)
</script>
</body>
</html>
// b.html (iframe html)
<html>
<body>
<script>
(function() {
function exportAndView() {
console.log("test");
}
window.addEventListener("message", (event) => {
exportAndView()
})
})()
</script>
</body>
</html>
Then in a.html, you can try use the way1 or way2, like document.getElementById("original_preview_iframe").contentWindow.exportAndView().
exportAndView will not be called becuase the scope problem.

Categories

Resources