(1) i have a script that opens a new window (2)New window can change its location/url for some redirection (3) I want to execute window.postMessage to the final redirection page of the popup window which will the parent window will received
<script>
//open window
//pops will change its url for some redirection
var pops = window.open('http://est.com/test.php', 'Login with Test', "width=300px;heigth=500px;");
window.addEventListener("message",function(e) {
if (e.origin !== 'http://west.com') {
return;
}
alert(e.data);
},false);
</script>
<script>
//code below is from other origin 'http://est.com/finalredirect.php'
// 'http://est.com/finalredirect.php' is the final redirection page of the popup window
window.postMessage({'data': 'test'}, 'west.com');
</script>
Or is there another work around for this?
Related
I want to open a new window and send message to this window and then receive in another tab. I am doing this but it is not working.
if (id > 0) {
var w = window.open(testurl,"address");
w.postMessage("ddd", "address");
}
new window is open but data is not showing.
Here is another window content.
<script>
window.addEventListener("message", receiveMessage, false);
function receiveMessage(event) {
alert(event.data);
}
</script>
Data is not alert. What is the problem?
targetOrigin is not the same as the name of the window you're opening. Origin is the value you get when alerting document.origin in the opened window.
This is what you should be passing as the second value to postMessage; not the name of the window.
I just found out that window.opener is not available in a window opened via window.open if the new URL is cross-domain, in IE. How do I detect window opener in IE
This will happen if the window starts in my domain, leaves it, and then comes back to my domain. I am attempting to have a social signup ( facebook, google, etc ) in the popup. When it completes it should close the new window and redirect the opener.
I know that Soundcloud is pulling this off, but I have no idea how. I see the URL change from theirs to Facebook, and then close.
After redirecting back to my site from 3rd party I run this:
var data = {
type : 'complete',
destination : '<?= $destination; ?>'
};
if ( window.opener ) {
window.opener.postMessage( JSON.stringify( data ), '*' );
window.close();
}
else {
alert( "Unable to find window" );
}
It alerts out in IE, even though the window was originally my domain, which then redirected to FB, then redirected back to me. I thought may since I open my site and redirect immediately from PHP that may be an issue. However even when I opened my site, did window.location.href = 'facebookssite.com' it still complained when returning.
NOTE
Social signups do not work for google, FB, etc within an iframe. I believe they disallow them for security reasons.
Do it the other way around. Track the state of the child popup window from the main (opener) window, and you could easily know when the child window has been navigated back to you domain, so you could "talk" to it again. But don't close the child window by itself. Let the opener window obtain the result from the child window and then close it.
For example, main.html:
<!DOCTYPE html>
<head>
<title>main</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<script>
window.addEventListener("message", function(ev) {
if (ev.data.message === "deliverResult") {
alert("result: " + ev.data.result);
ev.source.close();
}
});
function Go() {
var child = window.open("child.html", "_blank", "height=200,width=200");
var leftDomain = false;
var interval = setInterval(function() {
try {
if (child.document.domain === document.domain) {
if (leftDomain && child.document.readyState === "complete") {
// we're here when the child window returned to our domain
clearInterval(interval);
alert("returned: " + child.document.URL);
child.postMessage({ message: "requestResult" }, "*");
}
}
else {
// this code should never be reached,
// as the x-site security check throws
// but just in case
leftDomain = true;
}
}
catch(e) {
// we're here when the child window has been navigated away or closed
if (child.closed) {
clearInterval(interval);
alert("closed");
return;
}
// navigated to another domain
leftDomain = true;
}
}, 500);
}
</script>
</head>
<body>
<button onclick="Go()">Go</button>
</body>
child.html:
<!DOCTYPE html>
<head>
<title>child</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<script>
window.addEventListener("message", function(ev) {
if (ev.data.message === "requestResult") {
// ev.source is the opener
ev.source.postMessage({ message: "deliverResult", result: true }, "*");
}
});
</script>
</head>
<body>
Go to example.com
Then click the browser Back button when ready.
</body>
Tested with IE10.
Due to security reason, window.opener is removed when redirecting to a different domain. The browser does not bother to restore the window.opener when you're back. In your case, you could try:
1) Do your authentication inside an iframe if possible instead of using redirect.
2) In your case, I see that you need to post the data back to the parent window. You could try this instead:
In your opened window, just store your data and close normally.
var data = {
type : 'complete',
destination : '<?= $destination; ?>'
};
window.hasData = true;
window.data = data;
window.close();
Your parent window has access to your opened window and can handle its close event:
openedWindow.beforeunload = function (){
//here you could access this.data or openedWindow.data because you're on the same domain
if (this.hasData){
}
//Reason we have this check is because the beforeunload event fires whenever the user leaves your page for any reason including close, submit, clicking a link, ...
}
3) A workaround: Use a timer in your parent page to check for the closed property of the openedWindow
setInterval(function(){
if (openedWindow.closed){
}
},1000);
4) Another solution using localStorage as you're on the same domain. You parent page can listen to the event
window.addEventListener("storage", function(event){
}, true);
Your openedWindow code:
var data = {
type : 'complete',
destination : '<?= $destination; ?>'
};
if (localStorage){
localStorage.setItem(JSON.stringify(data));
}
window.close();
From your iframe, webpage, on yoursite.com ... open a new window on yoursite.com
The window redirects itself to Google, Twitter, whatever
Once done, the OAuth redirect returns the window to a page on yoursite.com
The new window, because it has the same origin as the page that opened it, can communicate via window.open
Use localStorage or IndexedDB to communicate between windows that are showing documents from the same domain but which don't have a reference to each other.
Simply have a high-speed timer checking for the data, saving another piece of data to acknowledge receipt and the other window can find it and close.
In short - you use localStorage to pass commands and can even have a library to do this and delete the commands once they are executed, and post the return values.
You can use use window.postMessage(), which is provided for this exact scenario.
Explanation: https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
In my company we've different domains and there's the case where the intranet's site must get the our public website (to finally get rid of the maintenance of duplicated data).
Inspired in Ben Vinegar i've come to this solution simple solution avoiding the :
Call to domain webpage (in my case with the same name as the external one)
local 'getInfo.php'
<?php
$idSp = (isset($_GET['idSp'])?$_GET['idSp']:null);
echo file_get_contents('http://192.168.1.10/folder/getInfo.php?idSp='.$idSp);
?>
External 'getInfo.php' return
<?php
echo '<script>window.opener.manageDisplay('.$getRes.','.$isOK.');</script>';
if($auto_close){ echo "<script>window.close();</script>"; }
?>
In my parent jsp page I've used:
function popUpClosed() {
window.location.reload();
}
And in child (popup window) I've used:
<script type="text/javascript">
window.onunload = function() {
if (window.opener && !window.opener.closed) {
window.opener.popUpClosed();
}
};
</script>
by this code, parent window is reloading after inserting data from popup window but popup window is not closing, I've to manually close the popup window. How can the popup window be made self close??
To close the window in your popup change the code like this:
<script type="text/javascript">
window.onunload = function() {
if (window.opener && !window.opener.closed) {
window.opener.popUpClosed();
}
window.close();
};
</script>
Refer here: How to close the current window.
onunload is called whenever your page unloads.
If you are posting data, by a submit button, you are unloading the document.
This is not the same as closing the windows.
If you want to capture only the close of the window, you should use something like:
window.onbeforeunload = windowExit;
function windowExit(){
//do somethng
//check that you are not submitting.
}
Here are two sample functions that open and close a popup window. If you create your window within a variable, you can then target the window you've opened, meaning you can close it.
<script>
function openWin()
{
myWindow=window.open("","","width=200,height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
}
function closeWin()
{
myWindow.close();
}
</script>
I want to open a page in a new tab in Google Chrome with window.open(), but I don't want that window to gain focus after it's opened, but to stay in the background.
Is this possible? It only has to work on Google Chrome. It can also use the Google Chrome extension API.
Thanks
The proper way would be to use extension API:
chrome.tabs.create({url: "http://...", selected: false});
Code should be placed in a background page. If you need it inside a content script you can pass a message to a background page, like so:
//content script
chrome.runtime.sendMessage({link: link});
//background page
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if(message.link) {
chrome.tabs.create({url: message.link, selected: false});
}
});
window.open(url, name, features);
window.focus();
You will see the new window for a short moment though.
There is a way out in all the browser
function openURL(url, opt){
if (opt == 0){ // current window
window.location = url;
}else if (opt == 1){ // new window
window.open(url);
}else if (opt == 2){ // background window
window.open(url); self.focus();
}
}
so By using this you can do anything you want.
openURL( "http://www.google.com", 0 ) --> open in same window
openURL( "http://www.google.com", 1 ) --> open in new window
openURL( "http://www.google.com", 2 ) --> open in new window but in background.
Yes you can do that just use:
var myWindow = window.open(url,name,features);
myWindow.blur();
Activate parent window from child or activate self once child is opened.
Have a flash player that pops out into a separate popup browser window. And on the source page the flash player just displays a message that it is currently popped out.
Now if the user navigates away from the source page (to another page on the same domain) how do i get a reference to the popup or just detect if its open (using javascript on the new page)?
Figured this out. Had to have a javascript timer in the popped out window that trys to execute a function in the parent window that if exists will simply hide the player.
example
Popout window script
<script>
if(window.opener!=null)
setTimeout("popCheck();",2000);
function popCheck()
{
//Use try catch to prevent premission denied msgs in
//case parent window is on different domain
try
{
window.opener.setPoppedOut();
}
catch(e)
{
}
//Check Every 2 seconds
setTimeout("popCheck();",2000);
}
window.onbeforeunload = function()
{
//Used to facilitate popin on window close
if(window.opener!=null)
{
try
{
window.opener.setPoppedIn();
}
catch(e)
{
}
}
}
</script>
Parent window script
<script>
//Save the previous contents so that we can restore them later.
window.popoutContent = document.getElementById("popoutContent").innerHTML;
function setPoppedOut()
{
document.getElementById("popoutContent").innerHTML = "Player is Popped Out";
}
function setPoppedIn()
{
document.getElementById("popoutContent").innerHTML = window.popoutContent;
}
</script>