How to send child page value to parent page? - javascript

I have two pages parent page and child page, I have to add the selected value from child page to parent page. The below is my code for parent page.
function lookup(){
window.open('https://c.ap4.visual.force.com/apex/accountpopup','popuppage','width=400,toolbar=1,resizable=1,scrollbars=yes,height=400,top=100,left=100');
}
function updateValue(param)
{
document.getElementById("name").value = param;
}
And below is my child/popup page code:
function callaccount(param){
var parent1=window.dialogAruments;
var v=param;
parent1.updateValue(param);
window.close();
}
the popup is not closing and sending values to parent page

You can use window.opener. Please note that there are other functions in window like window.open, window.self, window.top and window.parent.
But in your case, window.opener is more relevant, because it refers to the window which called window.open(...)
So, your function should be:
function callaccount(param){
var parent1=window.dialogAruments;
var v=param;
window.opener.updateValue(param);
window.close();
}
Thanks !

Use jQuery local storage
Your code should look like this page1 where you want to pass value:
if (typeof(Storage) !== "undefined") {
// Store
localStorage.setItem("variable", "value");
}
else {
console.log("Sorry, your browser does not support Web Storage...");
}
Your page2 where you need that data:
if (typeof(Storage) !== "undefined") {
// Retrieve
console.log(localStorage.getItem("variable"));
}
else {
console.log("Sorry, your browser does not support Web Storage...");
}
View output in console, and let me know it will helps you or not !

Use window.opener
You need to use window.opener as below in you child page.
childWindow.opener.document.getElementById('<id from parent form>').value = '123';
The opener property returns a reference to the window that created the window.
When opening a window with the window.open() method, you can use this property from the child window to return details of the parent window.

Related

Redirect to Parent URL from callback after using window.open

I'm trying to redirect the callback URL back to the parent window that is calling window.open. Currently the callback URL is opening inside the child window spawned from the parent.
Parent Window => Opens child window for authentication => user authenticates and is redirected to this child window. How do I redirect to the Parent Window?
Here is the call to window.open
newwindow = window.open(response.data.auth_url,'Etsy','height=800,width=1000');
if (window.focus) {
newwindow.focus()
}
Any idea how to accomplish this?
To communicate between windows use Postmessage
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
Your scenario might be that the child window sends a message to the parent window that in turn closes the child window and redirects to the final url.
Here's the solution I came up with if anyone else runs into this issue.
In my angularJS Controller file I check for the two pieces of info I need from the callback URL:
if ($state.params.oauth_token && $state.params.oauth_verifier) {
/* This closes the child window */
$window.close();
var params = {
oauth_token: $state.params.oauth_token,
oauth_verifier: $state.params.oauth_verifier
};
/* process the info ... */
}
I also poll to see when the callback URL is made and redirect the parent window
win = window.open(response.data.auth_url,'Etsy','height=800,width=1000');
var pollTimer = window.setInterval(function() {
try {
if (win.document.URL.indexOf(response.data.callback_url) != -1) {
window.clearInterval(pollTimer);
$state.go("etsy.connected");
}
} catch(e) {
// Error Handling
}
}, 500);

How to get count of browser open window or tab? [duplicate]

I have a html page. In the body of the page I am calling onload event which calls javascript function to open a pop up window. here is the code:
var newWindow = null;
function launchApplication()
{
if ((newWindow == null) || (newWindow.closed))
{
newWindow = window.open('abc.html','','height=960px,width=940px');
}
}
when I move to another page, and come back to that page again, popup reopens, although it is already opened. Please guide me to proper direction so that if pop up is already open then it should not open again. I tried document.referred but it requires the site online, currently I am working offline.
newWindow = window.open('abc.html','com_MyDomain_myWindowForThisPurpose','height=960px,width=940px');
Give the window a name. Basing the name on your domain like this, prevents the chances of you picking a name someone else happened to choose.
Never make up a name that begins with _, those are reserved for special names the browser treats differently (same as with the "target" attribute of anchor elements).
Note that if the window of that name was opened with different options (e.g. different height), then it'll keep those options. The options here will only take effect if there is no window of that name, so you do create a new one.
Edit:
Note that the "name" is of the window, not of the content. It doesn't affect the title (newWindow.document.title will affect that, as of course will code in abc.html). It does affect other attempts to do stuff across windows. Hence another window.open with the same name will reuse this window. Also a link like clicky! will re-use it. Normal caveats about browsers resisting window-opening in various scenarios (popup-blocking) apply.
To open a window and keep a reference to it between page refresh.
var winref = window.open('', 'MyWindowName', '');
if(winref.location.href === 'about:blank'){
winref.location.href = 'http://example.com';
}
or in function format
function openOnce(url, target){
// open a blank "target" window
// or get the reference to the existing "target" window
var winref = window.open('', target, '');
// if the "target" window was just opened, change its url
if(winref.location.href === 'about:blank'){
winref.location.href = url;
}
return winref;
}
openOnce('http://example.com', 'MyWindowName');
You can check if the window is open or closed by re-assigning a reference to it when it closes. Example:
var newWindow;
var openWindow = function(){
newWindow = newWindow || window.open('newpage.html');
newWindow.focus();
newWindow.onbeforeunload = function(){
newWindow = null;
};
};
Use the "closed" property: if a window has been closed its closed property will be true.
https://developer.mozilla.org/en-US/docs/Web/API/Window/closed
When you move on another page (on the same domain), you can re-set the window.open variable with popup page like this :
https://jsfiddle.net/u5w9v4gf/
Step to try :
Click on Run (on jsfiddle editor).
Click on Try me (on preview).
Click on Run to move on another page, the variable will be re-set.
Code :
window.currentChild = false;
$("#tryme").click(function() {
if (currentChild) currentChild.close();
const child = window.open("about:blank", "lmao", 'width=250,height=300');
currentChild = child;
//Scrope script in child windows
child.frames.eval(`
setInterval(function () {
if (!window.opener.currentChild)
window.opener.currentChild = window;
}, 500);
`);
});
setInterval(function() {
console.log(currentChild)
if (!currentChild || (currentChild && currentChild.closed))
$("p").text("No popup/child. :(")
else
$("p").text("Child detected !")
}, 500);

Pass variable from child window to parent window between 2 applications

I have opened a child window using a showModal dialog where the URL points to a different website as the main window does.
I want to pass some variables from the child window to the parent window using the script below.
Script used in Parent window:
function Open() {
var Return;
Return = window.showModalDialog("https://example.com/ChildApp/ChildForm.aspx", "", "dialogWidth:670px;dialogHeight:600px;")
alert(Return.passVariable);
}
The URL for the parent window is something like this: https://example.com/MainApp/MainForm.aspx
Script used in Child window:
function Close(parameter) {
var vReturnValue = new Object();
vReturnValue.passVariable= parameter;
window.returnValue = vReturnValue;
window.close();
}
In the main window, Return returns null.
One more issue exists when I'm trying to get a reference of window.parent, it gives a null value in the child window.
Note: Here ChildApp and MainApp are two different applications.

How to redirect main window to URL from popup?

I have a pop-up window with a form in it. On submit of the form, I wish to redirect to a particular page, but on the parent window (not on the popup).
How can I achieve this using Javascript?
After Application of Josh Idea
I am calling a javascript function to submit a form, in this javascript, below is the mentioned code
So Can this be executed as i tried with this and its not working as per my need
function instant_popup_post()
{
var cid = document.getElementById('product').value;
var session_id = document.getElementById('sessid').value;
if(cid==30)
{
alert(document.getElementById('instantpop').onsubmit="opener.location.href = 'http://192.168.1.5/cppl11/bannerbuzznew/full_color_banner.php?&id=+cid+'&info_id=5&osCsid='+session_id;");
document.instantpop.submit();
}
else if(cid==31)
{
document.getElementById('instantpop').onsubmit="opener.location.href ='perforated_window_signs.php?&id='+cid+'&info_id=6&osCsid='+session_id;";
document.instantpop.submit();
}
else if(cid==32)
{
document.getElementById('instantpop').onsubmit="opener.location.href ='preprinted_stock_banner.php?&id='+cid+'&info_id=7&osCsid='+session_id;";
document.instantpop.submit();
}
}
plss help
From within the popup, you can use the opener property to reference the parent window...
opener.location.href = 'http://www.google.com';
You can also invoke functions on the parent window...
opener.functionName();
Of course, the good old same origin policy restrictions apply here
I would say to use showModalDialog, so you will be freezing the parent window, and after it is done, you can send a variable to parent and do the redirect:
MainWindow:
function ShowModalForm()
{
var urlToRedirect = window.showModalDialog('url');
if (urlToRedirect)
window.location = urlToRedirect;
}
Popup Window:
function buttonAcceptClicked()
{
//Do stuff you need
window.returnValue = "new url";
window.close()
}
Here is a lot of information about this.

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

I am writing an iframe based facebook app. Now I want to use the same html page to render the normal website as well as the canvas page within facebook. I want to know if I can determine whether the page has been loaded inside the iframe or directly in the browser?
Browsers can block access to window.top due to same origin policy. IE bugs also take place. Here's the working code:
function inIframe () {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
top and self are both window objects (along with parent), so you're seeing if your window is the top window.
When in an iframe on the same origin as the parent, the window.frameElement method returns the element (e.g. iframe or object) in which the window is embedded. Otherwise, if browsing in a top-level context, or if the parent and the child frame have different origins, it will evaluate to null.
window.frameElement
? 'embedded in iframe or object'
: 'not embedded or cross-origin'
This is an HTML Standard with basic support in all modern browsers.
if ( window !== window.parent )
{
// The page is in an iframe
}
else
{
// The page is not in an iframe
}
I'm not sure how this example works for older Web browsers but I use this for IE, Firefox and Chrome without an issue:
var iFrameDetection = (window === window.parent) ? false : true;
RoBorg is correct, but I wanted to add a side note.
In IE7/IE8 when Microsoft added Tabs to their browser they broke one thing that will cause havoc with your JS if you are not careful.
Imagine this page layout:
MainPage.html
IframedPage1.html (named "foo")
IframedPage2.html (named "bar")
IframedPage3.html (named "baz")
Now in frame "baz" you click a link (no target, loads in the "baz" frame) it works fine.
If the page that gets loaded, lets call it special.html, uses JS to check if "it" has a parent frame named "bar" it will return true (expected).
Now lets say that the special.html page when it loads, checks the parent frame (for existence and its name, and if it is "bar" it reloads itself in the bar frame. e.g.
if(window.parent && window.parent.name == 'bar'){
window.parent.location = self.location;
}
So far so good. Now comes the bug.
Lets say instead of clicking on the original link like normal, and loading the special.html page in the "baz" frame, you middle-clicked it or chose to open it in a new Tab.
When that new tab loads (with no parent frames at all!) IE will enter an endless loop of page loading! because IE "copies over" the frame structure in JavaScript such that the new tab DOES have a parent, and that parent HAS the name "bar".
The good news, is that checking:
if(self == top){
//this returns true!
}
in that new tab does return true, and thus you can test for this odd condition.
The accepted answer didn't work for me inside the content script of a Firefox 6.0 Extension (Addon-SDK 1.0): Firefox executes the content script in each: the top-level window and in all iframes.
Inside the content script I get the following results:
(window !== window.top) : false
(window.self !== window.top) : true
The strange thing about this output is that it's always the same regardless whether the code is run inside an iframe or the top-level window.
On the other hand Google Chrome seems to execute my content script only once within the top-level window, so the above wouldn't work at all.
What finally worked for me in a content script in both browsers is this:
console.log(window.frames.length + ':' + parent.frames.length);
Without iframes this prints 0:0, in a top-level window containing one frame it prints 1:1, and in the only iframe of a document it prints 0:1.
This allows my extension to determine in both browsers if there are any iframes present, and additionally in Firefox if it is run inside one of the iframes.
I'm using this:
var isIframe = (self.frameElement && (self.frameElement+"").indexOf("HTMLIFrameElement") > -1);
Use this javascript function as an example on how to accomplish this.
function isNoIframeOrIframeInMyHost() {
// Validation: it must be loaded as the top page, or if it is loaded in an iframe
// then it must be embedded in my own domain.
// Info: IF top.location.href is not accessible THEN it is embedded in an iframe
// and the domains are different.
var myresult = true;
try {
var tophref = top.location.href;
var tophostname = top.location.hostname.toString();
var myhref = location.href;
if (tophref === myhref) {
myresult = true;
} else if (tophostname !== "www.yourdomain.com") {
myresult = false;
}
} catch (error) {
// error is a permission error that top.location.href is not accessible
// (which means parent domain <> iframe domain)!
myresult = false;
}
return myresult;
}
Best-for-now Legacy Browser Frame Breaking Script
The other solutions did not worked for me. This one works on all browsers:
One way to defend against clickjacking is to include a "frame-breaker" script in each page that should not be framed. The following methodology will prevent a webpage from being framed even in legacy browsers, that do not support the X-Frame-Options-Header.
In the document HEAD element, add the following:
<style id="antiClickjack">body{display:none !important;}</style>
First apply an ID to the style element itself:
<script type="text/javascript">
if (self === top) {
var antiClickjack = document.getElementById("antiClickjack");
antiClickjack.parentNode.removeChild(antiClickjack);
} else {
top.location = self.location;
}
</script>
This way, everything can be in the document HEAD and you only need one method/taglib in your API.
Reference: https://www.codemagi.com/blog/post/194
I actually used to check window.parent and it worked for me, but lately window is a cyclic object and always has a parent key, iframe or no iframe.
As the comments suggest hard comparing with window.parent works. Not sure if this will work if iframe is exactly the same webpage as parent.
window === window.parent;
Since you are asking in the context of a facebook app, you might want to consider detecting this at the server when the initial request is made. Facebook will pass along a bunch of querystring data including the fb_sig_user key if it is called from an iframe.
Since you probably need to check and use this data anyway in your app, use it to determine the the appropriate context to render.
function amiLoadedInIFrame() {
try {
// Introduce a new propery in window.top
window.top.dummyAttribute = true;
// If window.dummyAttribute is there.. then window and window.top are same intances
return !window.dummyAttribute;
} catch(e) {
// Exception will be raised when the top is in different domain
return true;
}
}
Following on what #magnoz was saying, here is a code implementation of his answer.
constructor() {
let windowLen = window.frames.length;
let parentLen = parent.frames.length;
if (windowLen == 0 && parentLen >= 1) {
this.isInIframe = true
console.log('Is in Iframe!')
} else {
console.log('Is in main window!')
}
}
It's an ancient piece of code that I've used a few times:
if (parent.location.href == self.location.href) {
window.location.href = 'https://www.facebook.com/pagename?v=app_1357902468';
}
If you want to know if the user is accessing your app from facebook page tab or canvas check for the Signed Request. If you don't get it, probably the user is not accessing from facebook.
To make sure confirm the signed_request fields structure and fields content.
With the php-sdk you can get the Signed Request like this:
$signed_request = $facebook->getSignedRequest();
You can read more about Signed Request here:
https://developers.facebook.com/docs/reference/php/facebook-getSignedRequest/
and here:
https://developers.facebook.com/docs/reference/login/signed-request/
This ended being the simplest solution for me.
<p id="demofsdfsdfs"></p>
<script>
if(window.self !== window.top) {
//run this code if in an iframe
document.getElementById("demofsdfsdfs").innerHTML = "in frame";
}else{
//run code if not in an iframe
document.getElementById("demofsdfsdfs").innerHTML = "no frame";
}
</script>
if (window.frames.length != parent.frames.length) { page loaded in iframe }
But only if number of iframes differs in your page and page who are loading you in iframe. Make no iframe in your page to have 100% guarantee of result of this code
Write this javascript in each page
if (self == top)
{ window.location = "Home.aspx"; }
Then it will automatically redirects to home page.

Categories