开发者

Javascript submit() event is not fired up on exit (unload event)

I got page where HTML elements <form> and <iframe> are dynamically created with Javascript:

document.write('<iframe id="myIframe" name="myIframe" src="about:blank" style="display:none;"></iframe>');
document.write('<form id="myForm" name="myForm" method="post" target="myIframe" action="myURL.php" style="display:none;">');
document.write('<textarea name="d"></textarea>');
document.write('</form>');

Then some data is placed into <textarea> element and submitted:

var data = '';

function myOnClick()
{
    // combine data
    data += 'click|';

    if (data.length > 17)
    {
        // initiate after 3rd click
        mySubmit();
    }
};
function myOnUnload()
{
    if (data.length > 0)
    {
        mySubmit();
    }
};
function mySubmit()
{
    var form     = document.getElementById('myForm');
    var textarea = form.getElementsByTagName('textarea')[0];

    // set data
    textarea.innerHTML = data;
    // send data
    form.submit();

    // set var to default value
    data = '';
};

if (document.addEventListener)
{
    // Gecko browsers
    document.addEventListener('mousedown', myOnClick, false);
}
else if (document.attachEvent)
{
    // IE browsers
    document.attachEvent('onmousedown', myOnClick, false);
}

window.onunload = function()
{
    myOnUnload();
};

The problem is that clicking on the page data is combined and sent as it supposed to do on both Gecko and IE browsers in the same way. But when user is leaving the page and the data is set form.submit() is not initiated on Gecko browser though IE does it as I wanted to do.

For example, on the same page exists link <a href="http://www.google.com">Google</a> which user submits after he/she clicked anywhere on the page. Once user done that, data is set and need to be submited to myURL.php, but it's not.

UPDATE: This is the whole code http://pastebin.com/DF3DVLpG. By mentioning Gecko based browsers I had in mind other popular browsers such as Firefox, Opera, Chrome and Safari. Sorry for misleading.

What could be the problem: Javascript code, browser behaviour or something e开发者_如何学编程lse?


This MS Article could help with your issue.

http://support.microsoft.com/kb/331869

Not sure if that is your exact problem without seeing more of your code. If that is all of your code, it is very likely that is the problem.


I got it working by using other event - onbeforunload.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜