Opening new windows in Chrome after an AJAX request behaves like a pop-up

When a user clicks a button in my application, an ajax request is triggered. Following the success of this request, I generate a URL which I intend to open in a new tab. Unfortunately, when using Chrome and calling window.open within the success handler, the URL opens as a popup and gets blocked by popup blockers. It seems that Chrome may be mistakenly categorizing the asynchronous success code as not directly caused by the initial click event. Is there any way to address this issue without switching to synchronous ajax requests?

UPDATE Below is a snippet of code illustrating this problem:

$('#myButton').click(function() {
    $.ajax({
        type: 'POST',
        url: '/echo/json/',
        data: {'json': JSON.stringify({
            url:'http://google.com'})},
        success: function(data) {
            window.open(data.url,'_blank');
        }
    });
});

http://jsfiddle.net/ESMUA/2/

It is worth noting that my main concern is the URL opening in a separate window rather than a tab, rather than its blockage by popup blockers.

Answer №1

Consider adding the following code snippet to your project:

window.open(url,'_blank');

Tweak

It seems that bypassing popup-blockers for pages not directly triggered by a user action is challenging.

However, you can try this workaround to mimic a user action and hopefully avoid the popup-blocker:

var $a = $('<a>', {
        href: url,
        target: '_blank' 
    });

$(document.body).append($a);
$a.click();

Modification 2

In such cases, it might be better to maintain synchronous behavior.

If the new window shares the same origin, you do have some control over it using JavaScript.

$('#a').on('click', function(e){
    e.preventDefault();
    var wi = window.open('about:blank', '_blank');

    setTimeout(function(){ // asynchronous
        wi.location.href = 'http://google.com';
    }, 500);
});

Answer №2

Have you tried including async: false in your code? Give it a shot!

$('#myButton').click(function() {
$.ajax({
    type: 'POST',
    async: false,
    url: '/fetch/data/',
    data: {'json': JSON.stringify({
        endpoint:'http://example.com'})},
    success: function(response) {
        window.open(response.endpoint,'_blank');
    }
});
});

Answer №3

The technique that proved effective for me was:

const newTab = window.open('about:blank', '_blank');

myService.sendData('endpoint', requestPayload)
.then(function(response) {
    newTab.location.href = 'http://destinationwebsite.com/directory/page';
});

By opening the new tab prior to the synchronous call, capturing the reference to the window, and subsequently redirecting it upon receiving the asynchronous data via the promise.

Answer №4

Above, @pstenstrm shared a solution that almost worked for me, but I found an opportunity to enhance it with just one line of code. My ajax call was causing a delay of more than a second, resulting in a user-facing blank page issue. Thankfully, there is a straightforward way to inject HTML content into the new window we create.

For example:

$('#a').on('click', function(e){
    e.preventDefault();
    var wi = window.open('about:blank', '_blank');
    $(wi.document.body).html("<p>Please wait while you are being redirected...</p>");

    setTimeout(function(){ // async
        wi.location.href = 'http://google.com';
    }, 500);
});

This script populates the new tab with the message "Please wait while you are being redirected..." instead of displaying a blank page for a brief moment. I wanted to share this as a comment, but my reputation isn't high enough for commenting at the moment.

Answer №5

There is no foolproof method to determine if a pop-up window has been blocked by a browser's pop-up blocker. In Firefox and Internet Explorer 6 SP2, using the window.open function may return null if the tab or window was blocked.

https://developer.mozilla.org/en-US/docs/Web/API/Window/open#FAQ

If you want to know if your pop-up window was blocked by a pop-up blocker, you can check the return value of window.open(). In browsers like Mozilla/Firefox and Internet Explorer 6 SP2, it will be null if the window was not allowed to open. However, with most other pop-up blockers, there is no definitive way to determine this.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Assign an event listener to a collection of elements

Suppose I have an Array containing elements and another Array consisting of objects in the exact same index order. My goal is to add a click event for each element that will display a specific property of each object. For instance: myDivArray = [ div0, d ...

Enhancing Label and Input Elements with Dynamic CSS through jQuery Values

Edit : I am aware that their is a question mark in the jQuery, CSS and HTML. Due to it being generated automatically by Framework I cannot remove it. I'm trying to apply dynamic styling to the input and label elements in my HTML using jQuery. However ...

Writing in Node.js involves setting up a local DynamoDB for local development rather than running it in an actual Lambda

This straightforward aws.js script is used to execute dynamoDB operations locally. "use strict"; const AWS = require("aws-sdk"); AWS.config.dynamodb = { region: "eu-west-2", endpoint: "http://localhost:8000& ...

What is the best way to conceal the outline in a popup window?

I have successfully implemented a popup/modal window using JavaScript, but now I need to find a way to hide the outline map container. The initialization code for the map is as follows: self.mapDialogOptions = { autoOpen: false, m ...

Guide on sending JSON object to Angular custom components

I have implemented a custom element in Angular 7 using the CUSTOM_ELEMENTS_SCHEMA. My app.module.ts code is as follows: export class AppModule { constructor(private injector: Injector) {} ngDoBootstrap() { this.registerCustomElements( ...

Displaying content in a hidden div on click event

I am part of a volunteer group for prostate cancer awareness and support, and our website features multiple YouTube videos that are embedded. However, the page has been experiencing slow loading times due to the number of videos, despite them being hidden ...

Dealing with a 500 Error in Laravel 5 when using AJAX for POST requests

I've been following a tutorial for Laravel 5 and AJAX at https://www.youtube.com/watch?v=PRCm-7mEDkY, which seems to work fine. However, I'm encountering a 500 Internal Server Error with the Post Request. What could I be doing wrong? My goal is t ...

Encountered a problem when attempting to upload files to AWS S3 using React and React AWS S3

One issue I'm facing is receiving a strange response when trying to perform a put operation in my bucket. I am utilizing the react-aws-s3 package which only requires the bucket name, user keys, and region in its configuration. It's puzzling as t ...

Alter the command from 'require' to an 'import'

Utilizing https://www.npmjs.com/package/json-bigint with native BigInt functionality has been a challenge. In the CommonJS environment, the following code is typically used: var JSONbigNative = require('json-bigint')({ useNativeBigInt: true }); ...

Tool to stop automatic logouts on websites

In the web application where I work, users are automatically logged out after a period of inactivity. Unfortunately, I am unable to control this feature. The code responsible for logging the user out is as follows: var windoc = window.document; var timeou ...

Creating a custom event handler for form input changes using React hooks

A unique React hook was created specifically for managing form elements. This hook provides access to the current state of form fields and a factory for generating change handlers. While it works seamlessly with text inputs, there is a need to modify the c ...

Difficulty altering value in dropdown using onChange function - Material-UI Select in React app

Having trouble updating dropdown values with MUI's Select component. The value doesn't change when I use the onChange handler, it always stays the same even after selecting a new item from the dropdown. I made a functional example on CodeSanbox. ...

Enhance scrolling with a bounce effect

My goal is to implement a smooth scrolling experience with a bounce effect when the user over-scrolls, meaning they scroll too much to the top or bottom. I found an answer on Stack Overflow that explains how to achieve smooth scrolling, but I also want to ...

Obtain the total number of result entries

I'm working on a project involving JS and PHP. My goal is to call a PHP file using Ajax and have it return the count of result lines. I use echo for this: $connection = new PDO($source, $user); $query = "SELECT * FROM scores WHERE username = '" ...

The Angular modal service is failing to show up on the screen

I am having trouble implementing the angular modal service in my web application. When I click on the button, the modal does not appear. Can someone help me figure out what I am doing wrong? Builder View <div ng-controller="BuilderController as vm"> ...

Issue with VueJS instance: Unable to prevent default behavior of an event

Is there a way to disable form submission when the enter key is pressed? Take a look at the different methods I've attempted along with the code and demo example provided below. SEE PROBLEM DEMO HERE Intended outcome: When you focus on the input, pr ...

What could be causing React Router to fail in navigating to a nested route?

In my App.js file, I am implementing front-end routing using react-router-dom version 6.11.2: import "./App.css"; import { Route, RouterProvider, createBrowserRouter, createRoutesFromElements, } from "react-router-dom"; // Othe ...

Safari Browser does not currently offer support for MediaRecorder functionality

[Log] Webcam permission error Error: MediaRecorder is not supported I am facing an issue while trying to record audio. The Chrome browser allows audio recording without any problem, but Safari is throwing an error. global.audioStream = await navigator.m ...

What is preventing my video from filling the entire screen?

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=d ...

Executing several API endpoint requests using an array in Node.js

Having difficulty utilizing values from an array to make API calls to endpoints. The array contains necessary data to retrieve the information needed from the endpoint. However, when attempting to parse the JSON text received from the API call and extract ...