0

Looking for a bit of help please.

I need to check that a input is filled out then if the user leaves the screen to the tabs or back button etc then the post request happens.

 sendSMS: function(e) {
        if(this.to) {
            this.$http.post('/demo/send', message)
        }
 }

I need something to say when the input is not empty and if the user leaves the site area screen, i.e goes up towards the tabs or back button, then do the post request. So there will be no button been pressed to submit this, but rather than a check to see if the input is filled out and if the user leaves the screen.

How would I do this using VueJS in the above method I'm using?

theUnified
  • 9
  • 1
  • 5

1 Answers1

2

Run a js function on page close: Run JavaScript code on window close or page refresh?

You'll want to add the event listener in your ready function in Vue:

....
data:function(){
    return {sentRequest:false}
},
ready:function(){
    window.onbeforeunload = this.leaving;
    window.onblur = this.leaving;
    window.onmouseout = this.leaving;

},
methods:{
    leaving:function(){
        if(!this.sentRequest){
             //do stuff
             this.sentRequest = true;
        }
        return null;
    }
}
....
Community
  • 1
  • 1
Jeff
  • 24,623
  • 4
  • 69
  • 78
  • So in the beforeonload function is that the function to check a user as left the screen, should I then put my post request in there? – theUnified Mar 05 '16 at 16:02
  • yep, that function will run when the window is closed. there is no way to tell if a user changes to another tab – Jeff Mar 05 '16 at 16:16
  • What about if a user just moves above the screen window of the displayed site? Is that still the same? – theUnified Mar 05 '16 at 16:19
  • I updated my answer it looks like there is a way to tell if the user leaves the tab with `window.onblur`. I don't know what you mean by moves above the screen window – Jeff Mar 05 '16 at 16:22
  • added one more for `onmouseout` – Jeff Mar 05 '16 at 16:37
  • thats great but in ````leaving:function(){ console.log('User moved away'); return null; }```` the console is loggin every movement with the screen and not just once out of the screen . – theUnified Mar 05 '16 at 16:41
  • Think that would be ````window.onmouseleave = this.leaving;```` is that right? – theUnified Mar 05 '16 at 16:48
  • hmm I'm not sure which of these events is doing that. You may need to tweak I'm not sure how exactly these events are triggered. You could also add some logic to make sure this event only runs once, or maybe only once per second or so depending on your use case – Jeff Mar 05 '16 at 16:48
  • Sorry to be a complete pain but how would I do such thing to check it only does once etc – theUnified Mar 05 '16 at 17:03
  • added an example way to do that – Jeff Mar 05 '16 at 17:50