function log(name, va开发者_开发知识库lue)
{
mylog.push({'name':name, 'value':value});
}
function flush()
{
for (i = 0 ; i < mylog.length ; i++){
url_str += '&n[]=' + mylog[i].name + '&v[]=' + mylog[i].value;
}
url_str += '&r='+Math.floor(Math.random() * 100000);
var img = new Image();
var url = 'http://somedomain.com/pixel.php?' + url_str;
img.src = url;
}
if (window.attachEvent)
window.attachEvent('onunload', flush);
else if (window.addEventListener)
window.addEventListener('unload', flush, false);
I'm working on some code that tracks user interactions to find hotspots on a page. Most of it is done already and works on most browsers, but I'm currently stumped on Safari 5.0.5/Mac 10.6 (BTW, it can also be replicated with Safari 5.0.1 on Windows XP). The part that's giving me difficulty is link clicks during page transfers. For example, the code below takes me to someotherpage.html:
<form onclick="log('LINK_CLICKED', 'some other page'); this.submit();" action="someotherpage.html">Some other page</form>
The site takes me to someotherpage.html in all browsers, but only Safari 5.0.5/Mac 10.6 doesn't show a LINK_CLICKED in the logs. After doing some console checking in the Safari inspector, I found that that Safari had a "failed to load resource" error. I suspect this is because while the URL could be called, the browser had decided to move on(?).
In any case, I've tried the beforeunload event and using setTimeout to delay the page unload. I'm considering changing the HTML form altogether, but it's going to be quite an effort. Still, I'm open to it unless someone has ideas that has skipped my attention. Any suggestions on how it could work on Safari 5.0.5 (Mac 10.6)?
I think you are just running into a race condition that could be alleviated with a callback on the tacking pixel load.
function log(name, value, callback)
{
mylog.push({'name':name, 'value':value, 'callback':callback});
}
function flush()
{
for (i = 0 ; i < mylog.length ; i++){
url_str += '&n[]=' + mylog[i].name + '&v[]=' + mylog[i].value;
}
url_str += '&r='+Math.floor(Math.random() * 100000);
var img = new Image();
img.onload = logReady;
var url = 'http://somedomain.com/pixel.php?' + url_str;
img.src = url;
}
function logReady()
{
for (i = 0 ; i < mylog.length ; i++){
mylog[i].callback();
}
}
<form onclick="log('LINK_CLICKED', 'some other page', function() { form.submit(); });" action="someotherpage.html">Some other page</form>
精彩评论