pinksharpii
pinksharpii

Reputation: 527

Can we no longer use window.open()

I'm working on a client site to download a PDF after submitting a form by opening the PDF url in a new tab on form submission. But in Chrome, Safari and FF, they're all blocking the "popup". I have noticed a few articles talking about ways to prevent browsers from blocking window.open(). They're usually relating to ajax but I'm not using ajax. The other articles talk about how window.open() only works inside a click event. And even that doesn't work for me.

It doesn't make a ton of sense but in my example I try triggering a click and

<script>
    jQuery( document ).ready(function() {
        jQuery(".gform_confirmation_message a").on("click", function(e){
            e.preventDefault();
            var newWin = window.open("", "_blank");
            newWin.location = jQuery(".gform_confirmation_message a").attr("href");
        });

        jQuery(".gform_confirmation_message a").trigger("click");
    });
</script>

Even if I put a simple line outside jquery, doesn't work and gets blocked.

var newWin = window.open("", "_blank");

Also either of these on their own do absolutely nothing. It doesn't even bring up the popup blocked.

jQuery(".gform_confirmation_message a").trigger("click");
OR
jQuery(".gform_confirmation_message a").click();

I know browsers are hammering down on spam/ad security but this is ridiculous.

Upvotes: 0

Views: 696

Answers (1)

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94319

Popups are still possible. They just need to be triggered by a user action. Creating a fake click event is not considered a user action.

One way you can start the download is to simply redirect the page to the PDF with the correct content type set such that it will download immediately:

Content-Type: application/octet-stream

or

Content-Disposition: attachment

With HTML5 you can also start a download by creating a temporary <a> tag and set its download attribute to the file url. A virtual click event will still work.

var textFile = new Blob(["hello world"], {type: "text/plain"});
var blobUrl = URL.createObjectURL(textFile);

var a = document.createElement("a");
a.href = blobUrl;
a.download = "myTextFile.txt";
a.click();  // start the download

I know browsers are hammering down on spam/ad security but this is ridiculous.

Popups are annoying. There are plenty of ways to download a file without creating a useless popup window.

Upvotes: 1

Related Questions