2

We are monitoring our user actions in javascript to improve user experience in our website.

Javascript Code

$("html").bind("mousedown", function(e) {
     var img = new Image(); 
     img.src="http://monitor.example.com/track.gif?x="+e.pageX+"&"+e.pageY});

I am using image tag to avoid cross domain issues. It is working fine except the below scenarios.

Scenarios:

  1. Click on the anchor.
  2. Form Submit.
  3. Window reload.

How to solve this issue?

Kijewski
  • 25,517
  • 12
  • 101
  • 143
kannanrbk
  • 6,964
  • 13
  • 53
  • 94
  • try this http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy – Alex Nikulin Aug 03 '15 at 12:26
  • Why not create script tag with src? a lot of information is here http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy – Alex Nikulin Aug 03 '15 at 12:29

2 Answers2

1

The page will be gone before the image has a chance to download - the page refresh/post/link click will often happen quicker than it takes to download the image.

You would be better advised to perform the request of the image (or indeed any URL) synchronously, perhaps using an AJAX call. The execution will then continue after the image has finished downloading, rather than happening in parallel and causing the race condition you are currently seeing. Assuming that you have control over the remote server, this could be achieved using Cross-Origin Resource Sharing.

If CORS is not an option (you have no control over the remote server), you can synchronously call a server-side script on your server that calls on to the image on the remote server using curl or a similar tool in your programming language, as there will be no cross-origin restrictions on the server side.

Peter
  • 1,674
  • 4
  • 27
  • 44
  • Could you please let me know why I was downvoted? I'm always keen to hear how I could improve my answers. Thanks. – Peter Aug 03 '15 at 12:35
  • this is not possible onbeforeunload, besides 80% the 1x1px image WILL download before page closes (thats what google does) – Jacek Pietal Aug 03 '15 at 14:18
  • Yes that's why I called it a race condition - there is a chance it MIGHT download in time, but to be sure you need to block the main request while you perform the image request. Not sure why the OP needs to also do this before a page reload (there is no mousedown for a F5 for instance, and could it not have been done at any other point before the reload), but my solution should certainly work for form posts and link clicks. – Peter Aug 03 '15 at 14:21
1
#try this code
var monitor = function(e) {
     var img = new Image(); 
     img.src="http://monitor.example.com/track.gif?x="+(e.pageX || 'null')+"&y="+(e.pageY || 'null');
};

# reload page
$(document).bind("beforeunload", monitor);

# mouse down global
$(document).bind("mousedown", "*", monitor);

also, need to modify this because page refresh wont send pageX pageY

Jacek Pietal
  • 1,980
  • 1
  • 18
  • 27