Chrome Application is not closing - javascript

I have a close button for my chrome application and I've added the event listener to it. But now I am getting this error:
Uncaught TypeError: this.contentWindow.close is not a function
Coming from line 227 in the Chrome library itself
AppWindow.prototype.moveTo = $Function.bind(window.moveTo, window);
AppWindow.prototype.resizeTo = $Function.bind(window.resizeTo, window);
AppWindow.prototype.contentWindow = window;
AppWindow.prototype.onClosed = new Event();
AppWindow.prototype.onWindowFirstShownForTests = new Event();
AppWindow.prototype.close = function() {
this.contentWindow.close();
};
So I have multiple ways I've tried this first is as so
_.get = chrome.app.window.get.call(chrome,"main");
//second way
_.get = chrome.app.window.get("main");
//third way in dev panel
chrome.app.window.get("main").close();
//fourth way in dev panel
chrome.app.window.current().close();
Either way none of these will work because I think that there is something conflicting with the library itself. THOUGH everything works except for the close function.
Any suggestions as to why this would be?

Ok so looking further into my code I realized I made a very big hiccup like an amatuer and clogged the global scope. I initialized a variable close which in turn made window.close equal my new variable :0

Related

JavaScript force close a tab programmatically?

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).

Call Shutdown.exe from a JS function

I have this to close IE when the Exit button is pressed:
function uf_LoginCloseWindow()
{
window.close();
}
I want to do this:
function uf_LoginCloseWindow()
{
c:\windows\system32\shutdown.exe -f -l
}
Can't seem to get it to work, I tried:
var objShell = new ActiveXObject("WScript.shell");
objShell.Run("C:\windows\system32\shutdown.exe");
All I can get out of the developer console is "The value of the property 'uf_LoginCloseWindow' is null or undefined, not a Function object"
Any ideas?
You can close the window, but you can't close the running program as a whole with javascript alone. That is outside of the scope of javascript's security. Don't try to find a hack to make it happen, as it is a horrible thing to do for people browsing the net.

insertElementAtSelection stopped working

In my Thunderbird Addon called PasteHyperlink, I have a routine that inserts an html element into the Message Compose Window.
This used to work in Thunderbird, but now I get this js error:
Error: TypeError: thiseditor.insertElementAtSelection is not a function
However, it seems that thiseditor gets defined because it doesn't launch the alert.
Here is the function's code which I've reduced to the basic functionality:
var thiseditor = gMsgCompose.editor;
if (!thiseditor){ alert("Dude, the gMsgCompose.editor is broken") };
let link = thiseditor.document.createElement("a");
link.setAttribute("href", "http://stackoverflow.com");
link.textContent = "Display Text";
thiseditor.insertElementAtSelection(link, false);
MDN has this documentation, but I can't find anything anywhere that talks about why this is broken or what changed under the hood in Thunderbird 45.
Why did this quit working, and what should I do instead?
Well, I think I figured it out. I changed this:
var thiseditor = gMsgCompose.editor;
to this:
var thiseditor = gMsgCompose.editor.QueryInterface(Components.interfaces.nsIHTMLEditor);
Funny thing, it worked the first way for quite a long time. I don't know what changed in Thunderbird, though.

Javascript variable undefined in IE until console displayed

I have a small piece of code for a template project I'm working on. There are three separate buttons, that point to three separate locations. In order to make it easier for content providers, I have these buttons calling minimal routines to load the next page.
The code is as follows:
/* navigation functions here for clarity and ease of editing if needed */
prevURL = 'ch0-2.html';
nextURL = 'ch2-1.html';
manURL = 'ch1-2.html';
function prevPage() {
window.location = prevURL;
}
function nextPage() {
window.location = nextURL;
}
function goManager() {
window.location = manURL;
}
This works perfectly in Firefox and Chrome, but seems to fail in Internet Explorer.
I open up the developer tools in IE (F12) and am presented with the message:
SCRIPT5009: 'manURL' is undefined
The location information (line 43, character 13) points to the "window.location = manURL" part of the code.
However, once the developer tools are open, if I hit F5 to reload the page, the button works without error until I close IE and reopen it, where it once again fails to respond and gives the same "undefined" error.
I'm baffled. Anyone have any ideas?
UPDATE
I know the variable declaration is poor, and that I can use window.location.href instead. What is relevant here is that the other two pieces of code, which are identical in all of these significant ways, work perfectly either way.
epascarello has put me on the right track. by removing all console.log commands, everything starts working. I'm just wondering why this happens, and would like to be able to give epascarello credit for helping me.
IE does not have console commands when the developer window is not open. So if you have them in there the code will not run. It will error out.
You can either comment out the lines or add in some code that adds what is missing.
if (typeof console === "undefined") {
console = {
log : function(){},
info : function(){},
error : function(){}
//add any others you are using
}
}
Try setting
window.location.href
instead of just window.location.
Source:
http://www.webdeveloper.com/forum/showthread.php?105181-Difference-between-window.location-and-window.location.href
Always define variables before using them ,being explicit (expressing the intention) is a good practice,
so define your variables like this,
var prevURL = 'http://google.com';
var nextURL = 'http://msn.com';
var manURL = 'http://stackoverflow.com';
You can try using
window.location.href
refer to this post for difference
Suggestion:
Make a jsfiddle.net for us so we could guide you easily

What causes the error "Can't execute code from a freed script"

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.

Categories