Beforeunload event listener


So I’m trying to execute a command with the help of ‘’ or onbeforeunload.

I’ve added an event listener to a js node in the setup part and it seems to at least do a console.log on refresh/close of browser window. The part that I’m missing is actually passing some values to the listener. I guess this is more a general js question rather than noodl. If I create the event listener in the setup part of the JS node, how do I change values within the listener function later?

What I’m hoping to achieve is to ‘remove id’ from a collection node at closing/refresh time of a client window. And so on ‘setup’ I might not have the ID ready yet.

Thanks for helping!

Perhaps something like this?

setup: function(inputs, outputs) {
   var self = this;
   window.addEventListener("beforeunload", function (event) {
      var collection = Noodl.Collection.get("lol");
      //or var collection = inputs.collection; 
      collection.remove(self.myId); //'this' is the same object in both setup and run
run: function(inputs, outputs) {
   if(inputs.something) {
      this.myId = inputs.someId; //'this' is the same object in both setup and run

However, I’m not sure if Noodl will have time to do a collection sync or global update before the browser is reloaded so if you’re depending on a persist mode on your collection that will probably not work.

thanks for the tip!

I’m actually returning ‘false’ on: “collection.contains(item)” for my item. Which is odd since it’s there.
If I perform a “collection.get(index)” I get the item back (the ID’s between get and contains match, but I’m getting it back in ‘get’ but not in ‘containts’). Since I don’t know the index location of the item, I have to rely on the ID - contains.

Is there a way to format the ID somehow? I’m using a unique ID for model items in the collection so not sure if it’s not reading that properly.

Thanks again!

Actually… is ‘item’ in “collection.contains(item)” an ID of the model that I need to pass? Or is it some other value?


You should provide the Model object in the collection.contains(model) call. So if you only have the ID you can do:


However you should preferably also check if the ID exists first (since the Model.get(id) will return an empty model if the id does not exist already). So:

1 Like

I believe you were right about this. I do see the process of ‘removal’ go through on the client browser but it does not sync across all clients. Poop. Thought it was a good idea :slight_smile:

Any ideas/ways of how I could ‘sync’ as a last message from a client quitting?

I believe I have something of a workaround:

window.addEventListener("beforeunload", function (event) {

ping is attached to a ‘send message’ node which then if any other clients are running takes care of things. :slight_smile: Still, this relies on at least 1 other client to have a window open.

1 Like