开发者

javascript - window.open within XMLHttpRequest onreadystatechange anon. function

Here is what I'm trying to do:

httpReq.onreadystatechange = function() {
    if (httpReq.readyState == 4) {
        if (httpReq.status == 200) {
            var response = httpReq.responseText;
  开发者_StackOverflow中文版          if (response == "-2") document.shortener_form.urlField.value = "";
            else {
                document.shortener_form.urlField.value = response;
                window.open("http://example.com", '_blank');
            }
        } else {
            document.shortener_form.urlField.value = "Error!";
        }
    }
};

The window.open function on line 8 is not executing. It works everywhere else, just not within that anonymous function. I'm terrible at Javascript, I've searched Google and SO however found no answer. Thanks.

Edit: by the way, the function works everywhere else on the page and script, so I've isolated the problem to be within this anonymous function.


This may be a browser setting. Most browsers these days default to blocking popups (i.e. calls to window.open) that aren't triggered by a user-initiated event. This would cause popups to work inside e.g. a click or keyup handler, but not within an asynchronously-triggered function like your ready-state handler.

Check to see whether window.open works in other asynchronous code:

<script>
    window.setTimeout(function() {
        window.open("http://example.com", '_blank');
    }, 1000);
</script>

If this fails in your browser (as it does in mine), you're probably running into a popup blocker.


It is a popup blocker problem. Your browser doesn't want to allow window.open() unless it is the direct result from a user action (e.g. mouse click).


Is this line being executed or throwing an error:
document.shortener_form.field.value = response;

I noticed that it's different from the lines above and below it:
document.shortener_form.**urlField**.value = ""; (note the *'s) was that intentional?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜