I cannot get any data if I use different domains. If I run it on the same server, no problem with it - message is obtained.
index.html:
<head>
<title>Test 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function popupResize() {
var popup = window.open('popup.html', '', 'resizable=yes,scrollbars=yes,width=500,height=500');
// var popup = window.open('https://foo/index.html', '', 'resizable=yes,scrollbars=yes,width=500,height=500');
window.addEventListener(
'message',
function(event) {
console.log(event.data);
},
false
);
}
</script>
</head>
<body>
Go!
</body>
popup.html:
<head>
<title>Game history details</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
function postSize() {
var h = 100;
var w = 200;
opener.postMessage([h, w], '*');
}
</script>
</head>
<body onload="postSize();">
test 1
</body>
How to get it working using different servers?
Problem 1
popup.addEventListener(
You need to listen for the event on your original window, not on the popup. The popup is where the message comes from, not where it is sent.
Use window.addEventListener( or just addEventListener(.
Problem 2
{h, w}
ES6 shorthand property names are not supported by IE, Opera, Safari or Android Mobile. They are best avoided.
Problem 3
parent.postMessage({h, w}, '*');
You are sending a message to the opening window, not the parent frame. There is no parent frame (so parent recurses onto window).
That should be:
opener.postMessage({h: h, w: w}, '*');
Problem 4
<script type="text/javascript">
var popup = window.open('popup.html', '', 'resizable=yes,scrollbars=yes,width=500,height=500');
Your script does not have permission to open a new window except in response to a user event. That code needs moving into a function and then called from, for instance, a click event.
If I run it on the same server, no problem with it - message is obtained.
It is the combination of problems 1 and 3 that cause this. You are binding an event handler to the popup (which you can only do from the opening window if it is on the same origin) and you are posting a message from the popup to itself (because parent === window).
Complete, albeit not best practise, code that works in my tests:
http://localhost:7007/index.html
<!DOCTYPE html>
<html>
<script>
addEventListener("message", function (event) {
document.body.appendChild(document.createTextNode(event.data));
});
function pop() {
window.open("http://127.0.0.1:7007/popup.html");
}
</script>
<input type="button" onclick="pop()">
http://127.0.0.1:7007/popup.html
<!DOCTYPE html>
<html>
<script>
opener.postMessage([123, 456], '*');
</script>
<h1>popup</h1>
The eventListener should be attached to window instead of popup:
window.addEventListener(
'message',
function (event) {
console.log(event.data);
},
false
);
In your child window (popup), you are posting a message to the parent window, but the eventListener is attached to the child window instead.
Related
This question already has answers here:
Javascript - arrow functions this in event handler?
(4 answers)
Closed 5 years ago.
Background
I'm just giving jQuery a go and for an hour, I could not hide an element using $([selector]).hide([milliseconds]), which in my sample code, is called when I click the element, in this case the anchor tag <a>. But I got it working in the end, but I don't understand why so. The only change I needed to make using the function keyword, instead, so this:
Note: Examples used this not "a", see edits
event => {
$(this).hide(2000);
}
into this
function(event){
$(this).hide(2000);
}
Question
Why does using function work and using an 'arrow' function doesn't? Is there a difference between the two?
My source code, for testing:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<style>
a.test{
font-weight: bold;
}
</style>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<!--<script src="https://code.jquery.com/jquery-1.10.2.js"></script>-->
</head>
<body>
jQuery
<script>
// $(document).ready(function () {
// // $("a").click(event => {
// // alert("Thanks for visiting!");
// // //prevents the opening of the link (what are the default events of other events types?)
// // event.preventDefault();
// // //Special Effects - http://api.jquery.com/category/effects/
// // });
// });
$("a").click(function(event){
event.preventDefault();
$( this ).hide(2000);
});
$("a").addClass("test");
</script>
</body>
</html>
Arrow function does not create a new scope tethered to this. So, to get around this, just use a normal function (like bellow). Alternatively, you could do $(event.currentTarget).hide(2000); inside your arrow function.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<style>
a.test{
font-weight: bold;
}
</style>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<!--<script src="https://code.jquery.com/jquery-1.10.2.js"></script>-->
</head>
<body>
jQuery
<script>
$("a").click(function(event) {$(this).hide(2000)});
$("a").addClass("test");
</script>
</body>
</html>
Case 1:
var printWindow = window.open("", "print_window");
if(printWindow) {
printWindow.addEventListener('load', function(){alert(1);}, false); //Everything works but this listener is never called
printWindow.document.write(printView);
printWindow.focus();
}
Case 2:
var printWindow = window.open("<html>useless random stuff</html>", "print_window");
if(printWindow) {
printWindow.addEventListener('load', function(){alert(1);}, false); //this is hit
printWindow.focus();
}
So, dynamically loading HTML to the new window document cancels the load event listener? Or am I really messing things up somewhere?
Need help :D
You've some document context problems. Have a look up to documentation and dummy examples for window.open.
Also inspect below snippet and give attention that how alert function should be called from different window namespace.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id="window_opener">Click me to load a new window</button>
<script type="text/javascript">
document.getElementById("window_opener").addEventListener('click', function(){
var badDocumentString = "<html><head><title>print window</title></head><body>I live in child window</body></html>";
var child = window.open()
childdoc = child.document
childdoc.write(badDocumentString);
childdoc.close();
child.addEventListener("load", function(){
child.alert("zeee germans"); //attention here
});
})
</script>
</body>
</html>
I want to open a link in new tab and immediately refresh my page in JavaScript. But when I open a new tab using window.open(), it does't reload my page. it waits for new tab to be closed then refresh my page.
Although it works in IE. But Chrome is waiting to child window to be closed.
$.ajax({
url: '/MailMan/Print'
, dataType: "json"
, type: "POST"
, success: function (result) {
if (result.success == true) {
window.open(
'/MailMan/Index/Building/1/Shift/1'
, '_blank'
);
window.location.reload();
}
}
});
The child page contains window.print() command in onload()of it. and when I close print dialog , main page refreshes successfully. This is my child page :
<head>
<meta name="viewport" content="width=device-width" />
<script>
window.onload = function () {
window.print();
}
</script>
</head>
<body>
</body>
I change my child window as below and it works for me. although it bring print dialog 1 sec later but it's not a big deal for me.
<head>
<meta name="viewport" content="width=device-width" />
<script>
window.onload = function () {
window.setTimeout(window.print(),1000
);
}
</script>
</head>
<body>
</body>
http://ahmedstudio.za.pl/firefoxerror/
It works in chrome, opera but doesn't get along with Firefox.
The whole javascript thing is not applying.
This is directly in my javascript.js:
window.onload = function() {
todo("body", 50);
alert("alert!");
setTimeout(function () {
todo("body", 0);
}, 1000)
}
function todo(element, size) {
//blahblah
}
Even if it doesn't actually solve your problem I'd like to share my findings about replacing event handlers with invalid function calls. I've composed this little fiddle:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
jQuery(function(){
$("body").on("load", function(){
$(this).append("Should not run")
});
});
</script>
</head>
<body onload="doesNotExist()">
</body>
</html>
Firefox, Explorer and Edge actually replace the <body> event handler. However, Chrome ignores the onload="doesNotExist()" and execute previous handler.
In the land of tag soup it's hard to decide which workaround is the correct one but it's definitively a bug that could explain your symptoms.
function load() {
//do stuff
}
and the appropriate
<body onload="load()"> </body>
This runs fine in me. I even tried to create a dummy page with this snippet but could not replicate it.Here is snippet.Since the snippet you shared does not contain jquery , i opt to use same code .
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script>
window.onload = function(){
_todo({
a:'body',
b:50,
alertFrom:'window.onload'
});
setTimeout(function(){
_todo({
a:'body',
b:0,
alertFrom:'setTimeOut'
});
},1000);
};
function _todo(options){
var a = options.a;
var b = options.b;
var c=options.alertFrom
alert(c +" "+a +" "+b);
};
</script>
</body>
</html>
Also note that there is a importance of semicolon after a function.
Here are couple of snapshots
I am currently using window.showModalDilog to open a modal pop up window which is not allowing the parent window to do any action.
But through Google search, I found that it is not the standard method and various browsers has stopped supporting this function.
In fact I am facing this problem in Opera. Opera gives me a Javascript error and stops execution at that point. Nothing can happen after that error.
So, I have only one option left and that is window.open.
But I want to disable parent window (likewise in showModalDilog).
I tried below code to do so:
$(window).load(function() {
window.opener.document.body.disabled=true;
});
$(window).unload(function() {
window.opener.document.body.disabled=false;
});
But that did not work.
I want to open an URL in the pop-up window and then do certain actions after the URL is opened, including submitting a form.
My code to open a pop up:
window.open("https://www.picpixa.com/wp-content/plugins/create-own-object/plugin-google-drive/index.php", "socialPopupWindow", "location=no,width=600,height=600,scrollbars=yes,top=100,left=700,resizable = no");
It would also help if I could open only one pop-up window on the clicking of multiple buttons. I mean if I click on "btn1" a pop-up named "temp" shall open. But if I click on "btn2" then instead of opening a new pop up "temp" shall reload.
I was able to make parent window disable. However making the pop-up always keep raised didn't work. Below code works even for frame tags. Just add id and class property to frame tag and it works well there too.
In parent window use:
<head>
<style>
.disableWin{
pointer-events: none;
}
</style>
<script type="text/javascript">
function openPopUp(url) {
disableParentWin();
var win = window.open(url);
win.focus();
checkPopUpClosed(win);
}
/*Function to detect pop up is closed and take action to enable parent window*/
function checkPopUpClosed(win) {
var timer = setInterval(function() {
if(win.closed) {
clearInterval(timer);
enableParentWin();
}
}, 1000);
}
/*Function to enable parent window*/
function enableParentWin() {
window.document.getElementById('mainDiv').class="";
}
/*Function to enable parent window*/
function disableParentWin() {
window.document.getElementById('mainDiv').class="disableWin";
}
</script>
</head>
<body>
<div id="mainDiv class="">
</div>
</body>
You can't make window.open modal and I strongly recommend you not to go that way.
Instead you can use something like jQuery UI's dialog widget.
UPDATE:
You can use load() method:
$("#dialog").load("resource.php").dialog({options});
This way it would be faster but the markup will merge into your main document so any submit will be applied on the main window.
And you can use an IFRAME:
$("#dialog").append($("<iframe></iframe>").attr("src", "resource.php")).dialog({options});
This is slower, but will submit independently.
Modal Window using ExtJS approach.
In Main Window
<html>
<link rel="stylesheet" href="ext.css" type="text/css">
<head>
<script type="text/javascript" src="ext-all.js"></script>
function openModalDialog() {
Ext.onReady(function() {
Ext.create('Ext.window.Window', {
title: 'Hello',
height: Ext.getBody().getViewSize().height*0.8,
width: Ext.getBody().getViewSize().width*0.8,
minWidth:'730',
minHeight:'450',
layout: 'fit',
itemId : 'popUpWin',
modal:true,
shadow:false,
resizable:true,
constrainHeader:true,
items: [{
xtype: 'box',
autoEl: {
tag: 'iframe',
src: '2.html',
frameBorder:'0'
}
}]
}).show();
});
}
function closeExtWin(isSubmit) {
Ext.ComponentQuery.query('#popUpWin')[0].close();
if (isSubmit) {
document.forms[0].userAction.value = "refresh";
document.forms[0].submit();
}
}
</head>
<body>
<form action="abc.jsp">
Click to open dialog
</form>
</body>
</html>
In popupWindow 2.html
<html>
<head>
<script type="text\javascript">
function doSubmit(action) {
if (action == 'save') {
window.parent.closeExtWin(true);
} else {
window.parent.closeExtWin(false);
}
}
</script>
</head>
<body>
Save
Cancel
</body>
</html>