Synchronous Ajax - does Chrome have a timeout on trusted events?

后端 未结 3 1735
忘了有多久
忘了有多久 2021-02-05 13:25

Situation

We have a situation, where we need to onclick-open a new tab in browsers after performing an XHR / Ajax request.

We do this by setti

3条回答
  •  清酒与你
    2021-02-05 14:11

    Your problem is not with XMLHttpRequest, but with delay (sync delay, maybe bug in WebKit/Blink)

    See example (http://jsfiddle.net/23JNw/32/ sandbox in Snippet don't allow pop-ups):

    function performSlowSyncronousRequest() {
        var endsIn, initial;
    
        delay = 5000;
    
        endsIn = new Date().getTime() + delay;
    
        for (; endsIn >= new Date().getTime();) {}//Delay
        window.open('http://www.thirtykingdoms.com');
    }
    
    
    

    Note: that sjax (XMLHttpRequest sync) is considered obsolete by some browsers is very bad for the user experience.

    I tried simulate click, but not work:

    function clickFire(evt){
    	var el, evtFake, pos;
    
    	el = document.createElement("a");
        el.href = "javascript:void(0);";
        el.innerHTML = "test";
    	el.onclick = evt;
    
    	document.body.appendChild(el);
    
    	pos = el.getBoundingClientRect();
    
    	evtFake = new MouseEvent("click", {
    		bubbles: false,	
    		cancelable: false,
    		view: window,
    		detail: 0,
    		screenX: window.screenX,
    		screenY: window.screenY,
    		clientX: pos.left + 1,
    		clientY: pos.top + 1,
    		ctrlKey: false,
    		shiftKey: false,
    		altKey: false,
    		metaKey: false,
    		button: 1,
    		buttons: 0,
    		relatedTarget: el
    	});
    	el.dispatchEvent(evtFake);
    
    	window.setTimeout(function() {
    		document.body.removeChild(el);
    	}, 1);
    }
    
    window.setTimeout(function() {
    	clickFire(function() {
    		window.open("http://stackoverflow.com");
    	});
    }, 1000);

    Note: The web browsers are very smart today and we will hardly get cheat them.

    Solution

    Don't use pop-ups ( I hate pop-ups :) ), try simulate "pop-up" using