简体   繁体   中英

How to close window without triggering 'window.onunload'?

I have an external program that opens an .hta file which contains some JavaScript:

function getLUTKey(key) {
  // Write txt file to user's file system
  var fso, fh;
  fso = new ActiveXObject("Scripting.FileSystemObject");
  fh = fso.CreateTextFile("PartID.txt", true);

  fh.Write(key);
  fh.close();
  self.close();
}

The idea is that the window contains a number of links for different parts which, when clicked, will write their respective "Part ID" to a file using the above js function. The previously-mentioned external program then waits in the background for this file to be created, then uses the file's contents.

However, in order to prevent the user from exiting without selecting a part - therefore never creating a file and leaving the external program to loop until a timeout triggers - I've added the following code:

window.onunload = function(){ getLUTKey('cancel') };

This creates another problem. When getLUTKey() is run with a valid ID, and it closes the window, the window.unload the code runs immediately after, overwriting whatever the ID in the file was with "cancel". My question is this:

Is there a way to close a window in javascript without triggering window.unload ?

I guess it's way easier for you to manage the state of your app. For example you can simply remove the handler of window closing after you're done with the function.

function getLUTKey(key){
// Write txt file to user's file system 
var fso, fh;
fso = new ActiveXObject('Scripting.FileSystemObject');
fh = fso.CreateTextFile('PartID.txt', true);     
fh.Write(key);          
fh.close();
window.onunload = null;
self.close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM