_blank got blocked as pop up how can i prevent this?

帅比萌擦擦* 提交于 2019-12-10 15:16:46

问题


I have created a pdf on the server when i use:

        function GetPdf(document) {


            //Stores the data and creates the html,pdf file
            $http.post('createpdf/', document).success(function(data){

                console.log(data.filename);

                window.open('download2/'+data.filename+".pdf", "_self");


            });

I get a error message pop up blocked in google chrome. When i use the option enable pop ups for this website it all works fine. Is there any way around this ? Because this could be confusing for some users.

But when i use:

window.open('download2/'+data.filename+".pdf", "_self");

It opens the page without warnings but then the main application is replaced by the pdf which is not the result i want to have.


回答1:


Browsers have strict rules about when they allow JavaScript to show a popup, but they can be summarized as "Only in response to a user action".

Receiving a response to an HTTP request is not a user action, so popups are banned.

The simple solution here is to not use JavaScript. The point of Ajax is to communicate with the server without leaving the page, but you're going to leave the page anyway so there isn't really any point in using Ajax.

Just use a regular form submission.

<form method="post" action="createpdf/" target="_blank">

… then have the server side script redirect to the URL of the created PDF instead of returning the URL as JSON.




回答2:


Pop up blocking is not an issue, but a native browser feature that protect the users from popup-hell. I would recommend to open the PDF in a modal popup instead of a new browser window.

With some jQuery code it is quite easy to implement: documentation is found here




回答3:


I guess you are using and external JavaScript library, I had the same issue on another Project, I used target="_tab" and it worked, I found this on this question. It's the way Chrome handles popup calls from JavaScript when you use libraries, I used Moment.js to trigger a similar event and got the same issue.




回答4:


You can always use an alternative route, for example instead of window.open function. You can use the window.location function, perhaps. Windows.location.replace which will relocate you in the same tab.

<script type="text/javascript">
<!--loc can be any changed to your window-->
var loc = "https://google.com/";
window.
window.onclick = function() {
   window.open(loc);
}
</script>

Try that :) window.open is being blocked because you are doing window.open without a click function. Most web browsers will block this feature for security purposes.



来源:https://stackoverflow.com/questions/34090835/blank-got-blocked-as-pop-up-how-can-i-prevent-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!