I had two domains for ex. domain1 and domain2, I am opening domain2/index.aspx page as popup from domain1/default.aspx page. While closing domain2 page i need to reload the domain1 page, i had given the javascript code as "Opener.Location.Reload();". I am getting Permission denied javascript error. Any ideas about this issue.
I found that setting a parentUrl variable in the popup window (gotten from a query string)
and then using :
window.opener.location.href = parentUrl;
works.
I don't know why, I think it's magic, but it works (tested on IE, chrome and Firefox).
You cannot read the value of window.opener.location.href, but you can set it to whatever url you want. I use this oddity to do the refresh.
Hope it helps
Certain properties and actions are specifically blocked in cross-domain scenarios. What you might be able to do is create a function on the parent that does the code you want, then call that function from the child.
Example:
// On the parent...
function DoTheRefresh()
{
location.reload();
}
Then, on the child:
opener.DoTheRefresh();
I have done this in the past, so I don't know for sure if it's still an option. I hope it works out for you :)
You can accomplish this by putting code in the parent window to detect when the child window has closed.
var win2;
function openWindow()
{
win2 = window.open('http://...','childwindow',...);
checkChild();
}
function checkChild() {
if (win2.closed) {
window.location.reload(true);
} else setTimeout("checkChild()",1);
}
Related
I'm running into a problem where some websites are failing to programmatically close:
window.close()
fails with:
web/Stores.war/RAPIDStorefrontAssetStore/AJAXUserInterface/javascript/FDBrowse.js:301 Uncaught TypeError: Cannot read property 'style' of null
at close (web/Stores.war/RAPIDStorefrontAssetStore/AJAXUserInterface/javascript/FDBrowse.js:301)
at <anonymous>:1:8
The offending website is: https://www.1800flowers.com/about-us-employment-opportunities?utm_medium=direct&utm_source=1800flowerscom
although this does happen to other ones too.
How can I force close? What is running in the close method which is failing? Some investigation reveals the document is failing to find some document element in a script the website is trying to run but how can I prevent it from running anything before closing? I tried to set the on_X methods to null to no success...
The problem you face is that this website has overidden the default window.close method with some other function.
To get around this, you should be able to call the original Window.close method from the Window object returned by window.open() in your master page.
var popup = window.open('...');
popup.close(); // should be the original Window.close method
But if for some reason, you absolutely want to close this method from inside the target page, then you can retrieve an original Window.close method from an iframe's contentWindow, and call this method on your broken page.
function close(){
console.log("It's bad to declare on the global scope");
}
console.log(window.close.toString());
window.close(); // our function
var iframe = document.createElement('iframe');
iframe.style.cssText = 'opacity:0;position:absolute';
iframe.src = 'about:blank';
iframe.onload = function() {
console.log(iframe.contentWindow.close.toString());
// you could call it like this
iframe.contentWindow.close.call(window);
// even if it will not work here because we didn't open the page programmatically
document.body.removeChild(iframe);
};
document.body.appendChild(iframe);
Here is a live plnkr to better demonstrates above code.
The following statement creates a new window using window.open(), rebinds window.close() to the original window, and subsequently closes both.
(window.close = (w => w.close() || w.close)(window.open()))()
Explanation
1800 Flowers have overriden the global window.close to close an arbitrary element.
This is evident when running console.log(window.close) in the browser.
console.log(window.close) // ƒ close(){document.getElementById("overlay").style.display="none"}
The error you cited is due to the override of window.close() and absence of document.getElementById('overlay').
Hence: "Cannot read property 'style' of null".
Therefore: to close 1800 Flowers programatically, window.close() must be rebound (short of finding an alternative method).
Trying to select the following link in html:
Nodequeue
with this Javascript:
jQuery("a:contains('Nodequeue')").trigger("click");
And I am receiving this error message:
Javascript console (:1): Unsafe JavaScript attempt to access frame with URL http://cdn.nprove.com/cpma/p/1/2/e/b/12ebf3bc368ry3ra.html?npuid=1310010225&rurl=&id=cpma-2n7eypbvio581300288437193&null=&r=366424962878227 from frame with URL http://www.benzinga.com/analyst-ratings/analyst-color/11/07/1742957/the-beef-stops-here. Domains, protocols and ports must match.
Any idea what might cause this?
I created a
JSFiddle of your code which you can look at and notice that in the console your error doesn't come up in Chrome 12 or FireFox 5. I'm not sure what version of jQuery you are using that is causing that or your DOM situation that may be triggering that error, however, try this potential fix:
(function(window, $) {
$.fn.triggerAnchor = function() {
return this.each(function(e) {
var href = $(this).attr('href');
window.location.href = href;
return false;
});
};
})(this, this.jQuery);
Then use with:
$("a:contains('Nodequeue')").triggerAnchor();
I don't think jQuery triggers anchors, and it certaintly doesn't trigger native click events. This is the closest thing I can think of to emulate that behavior.
You can see it 'working' here
Explanation of the code:
The code is simply a jQuery plugin that looks at the href attribute of anchor and sets the window location to that value. I wrote in the typical pattern of a wrapped closure to localize references to window and jQuery. I'm allowing you to call this on multiple anchors, but I'm assuming the average user would only need to run this once.
That error usually means you are making a javascript request from one frame to another. In this case, is the link in an iframe, or is jquery running in an iframe?
I want to get the references of all already opened child windows. is there any way? I am not using child = window.open(....) just using window.open(....) and opening multiple child windows.
If you don't want to change your current code, you can simply override window.open() function:
var openedWindows = [];
window._open = window.open; // saving original function
window.open = function(url,name,params){
openedWindows.push(window._open(url,name,params));
// you can store names also...
}
Run this code before calling window.open(). All the references to the opened windows will be stored in openedWindows array. You can access them anywhere you want
I don't believe you can, unless you know the windows' names, which I'm guessing you don't. (If you know their names, you can use window.open("", "name") to get a reference to them.)
The better option is, of course, to remember the reference returned from window.open in the first place — but you know that. :-)
Ok, I used the answers to this question in Oracle CRM onDemand to disable a select in a popup window executing the script from the parent window, and it worked! (I have no control over the generation of popup windows, they are opened by the application framework)
Let's see how I did it:
Context: In a detail page the user can add some info by clicking in a magnifying glass icon >>> a new window opens containing a search form, but a select is disturbing the administrator: If the user change its default value he/she will gain access to forbidden records!! Oh my God!
First Approach: Disable that select now!!
Attempt: I found the image's onclick attrib with my browser's dev tools (F12). There was a openAssocPopup method, and then i knew the name of the child window: 'OccamPopup1' :)
Okay! So let's do some magic (executed at the parent window):
window.open("","OccamPopup1").document.getElementById("frmSearch.AQ").setAttribute("disabled", true);
I think this may help, as this question helped to me too. You were right. Now i'm trying to wrap the child's document object within the parent's jQuery object so i can gain access to the entire child's DOM... but this is another story...
You would be best to name the windows using a prefix and a counter.
I needed to detect if a named window (i.e. CBCheckout) was already open and used this:
var signupWindow = window.open('','CBCheckout','toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=1,height=1');
try {
if (signupWindow.document.location.href == "about:blank") {
signupWindow.close();
signupWindow = undefined;
}
} catch (e) { }
This recaptured the reference to the named open window. If it didn't exist, you'd see a small window popup for a second.
If you know the possible names of the windows, you can cycle through the names, attempting to locate them.
I know that for safety reasons that this is not easy to achieve, however there would be a way to do so as firebug does...
Please help, would like to invoke some script in the page's context to achieve some effect...
Basically, I would like to achieve two functionality:
1. add jQuery to any web page automatically if not already exist.
2. when open certain address, call a method of that page to auto notify the server. (an ajax functionality of the page)
I have tried to inject on the body, no luck.
tried to get the window object, which however do not have access to call the function.
Will try to change the location to something like: javascript:alert('test inject');
Many thx.
OK, after reading some official documentation and the GreaseMonkey's source, I get the following method which basically works for me.
Hope it will save sb's hour:
var appcontent = document.getElementById("appcontent"); // browser
if (appcontent) {
appcontent.addEventListener("DOMContentLoaded", function (evnt) {
var doc = evnt.originalTarget;
var win = doc.defaultView;
var unsafeWin = win.wrappedJSObject;
// vote.up is the function on the page's context
// which is take from this site as example
unsafeWin.vote.up(...);
}, true);
}
}
Greasemonkey does that. If you are developing your own extension with similar functionality, you can use Components.utils.evalInSandbox.
I thought I'd found the solution a while ago (see my blog):
If you ever get the JavaScript (or should that be JScript) error "Can't execute code from a freed script" - try moving any meta tags in the head so that they're before your script tags.
...but based on one of the most recent blog comments, the fix I suggested may not work for everyone. I thought this would be a good one to open up to the StackOverflow community....
What causes the error "Can't execute code from a freed script" and what are the solutions/workarounds?
You get this error when you call a function that was created in a window or frame that no longer exists.
If you don't know in advance if the window still exists, you can do a try/catch to detect it:
try
{
f();
}
catch(e)
{
if (e.number == -2146823277)
// f is no longer available
...
}
The error is caused when the 'parent' window of script is disposed (ie: closed) but a reference to the script which is still held (such as in another window) is invoked. Even though the 'object' is still alive, the context in which it wants to execute is not.
It's somewhat dirty, but it works for my Windows Sidebar Gadget:
Here is the general idea:
The 'main' window sets up a function which will eval'uate some code, yup, it's that ugly.
Then a 'child' can call this "builder function" (which is /bound to the scope of the main window/) and get back a function which is also bound to the 'main' window. An obvious disadvantage is, of course, that the function being 'rebound' can't closure over the scope it is seemingly defined in... anyway, enough of the gibbering:
This is partially pseudo-code, but I use a variant of it on a Windows Sidebar Gadget (I keep saying this because Sidebar Gadgets run in "unrestricted zone 0", which may -- or may not -- change the scenario greatly.)
// This has to be setup from the main window, not a child/etc!
mainWindow.functionBuilder = function (func, args) {
// trim the name, if any
var funcStr = ("" + func).replace(/^function\s+[^\s(]+\s*\(/, "function (")
try {
var rebuilt
eval("rebuilt = (" + funcStr + ")")
return rebuilt(args)
} catch (e) {
alert("oops! " + e.message)
}
}
// then in the child, as an example
// as stated above, even though function (args) looks like it's
// a closure in the child scope, IT IS NOT. There you go :)
var x = {blerg: 2}
functionInMainWindowContenxt = mainWindow.functionBuilder(function (args) {
// in here args is in the bound scope -- have at the child objects! :-/
function fn (blah) {
return blah * args.blerg
}
return fn
}, x)
x.blerg = 7
functionInMainWindowContext(6) // -> 42 if I did my math right
As a variant, the main window should be able to pass the functionBuilder function to the child window -- as long as the functionBuilder function is defined in the main window context!
I feel like I used too many words. YMMV.
Here's a very specific case in which I've seen this behavior. It is reproducible for me in IE6 and IE7.
From within an iframe:
window.parent.mySpecialHandler = function() { ...work... }
Then, after reloading the iframe with new content, in the window containing the iframe:
window.mySpecialHandler();
This call fails with "Can't execute code from a freed script" because mySpecialHandler was defined in a context (the iframe's original DOM) that no longer exits. (Reloading the iframe destroyed this context.)
You can however safely set "serializeable" values (primitives, object graphs that don't reference functions directly) in the parent window. If you really need a separate window (in my case, an iframe) to specify some work to a remote window, you can pass the work as a String and "eval" it in the receiver. Be careful with this, it generally doesn't make for a clean or secure implementation.
If you are trying to access the JS object, the easiest way is to create a copy:
var objectCopy = JSON.parse(JSON.stringify(object));
Hope it'll help.
This error can occur in MSIE when a child window tries to communicate with a parent window which is no longer open.
(Not exactly the most helpful error message text in the world.)
Beginning in IE9 we began receiving this error when calling .getTime() on a Date object stored in an Array within another Object. The solution was to make sure it was a Date before calling Date methods:
Fail: rowTime = wl.rowData[a][12].getTime()
Pass: rowTime = new Date(wl.rowData[a][12]).getTime()
I ran into this problem when inside of a child frame I added a reference type to the top level window and attempted to access it after the child window reloaded
i.e.
// set the value on first load
window.top.timestamp = new Date();
// after frame reloads, try to access the value
if(window.top.timestamp) // <--- Raises exception
...
I was able to resolve the issue by using only primitive types
// set the value on first load
window.top.timestamp = Number(new Date());
This isn't really an answer, but more an example of where this precisely happens.
We have frame A and frame B (this wasn't my idea, but I have to live with it). Frame A never changes, Frame B changes constantly. We cannot apply code changes directly into frame A, so (per the vendor's instructions) we can only run JavaScript in frame B - the exact frame that keeps changing.
We have a piece of JavaScript that needs to run every 5 seconds, so the JavaScript in frame B create a new script tag and inserts into into the head section of frame B. The setInterval exists in this new scripts (the one injected), as well as the function to invoke. Even though the injected JavaScript is technically loaded by frame A (since it now contains the script tag), once frame B changes, the function is no longer accessible by the setInterval.
I got this error in IE9 within a page that eventually opens an iFrame. As long as the iFrame wasn't open, I could use localStorage. Once the iFrame was opened and closed, I wasn't able to use the localStorage anymore because of this error. To fix it, I had to add this code to in the Javascript that was inside the iFrame and also using the localStorage.
if (window.parent) {
localStorage = window.parent.localStorage;
}
got this error in DHTMLX while opening a dialogue & parent id or current window id not found
$(document).ready(function () {
if (parent.dxWindowMngr == undefined) return;
DhtmlxJS.GetCurrentWindow('wnManageConDlg').show();
});
Just make sure you are sending correct curr/parent window id while opening a dialogue
On update of iframe's src i am getting that error.
Got that error by accessing an event(click in my case) of an element in the main window like this (calling the main/outmost window directly):
top.$("#settings").on("click",function(){
$("#settings_modal").modal("show");
});
I just changed it like this and it works fine (calling the parent of the parent of the iframe window):
$('#settings', window.parent.parent.document).on("click",function(){
$("#settings_modal").modal("show");
});
My iframe containing the modal is also inside another iframe.
The explanations are very relevant in the previous answers. Just trying to provide my scenario. Hope this can help others.
we were using:
<script> window.document.writeln(table) </script>
, and calling other functions in the script on onchange events but writeln completely overrides the HTML in IE where as it is having different behavior in chrome.
we changed it to:
<script> window.document.body.innerHTML = table;</script>
Thus retained the script which fixed the issue.