Javascript window.open works in Chrome console but not as a snippet

冷暖自知 提交于 2019-12-11 04:43:04

问题


I'm relatively new to Javascript and I'm working on some little scripts to modify webpages that I work with often. One of the things I'm automating is opening certain links in tabs and so I don't have to do so manually.

If I put this line into my snippet and run it, nothing happens:

window.open("http://www.google.com");

But if I type it into the console and hit return, it opens a new tab with the url just fine. All of this is happening in the Inspector. Why does it work in one place but not the other? Is there a workaround?


回答1:


When Chrome detects a call to window.open() which does not originate from a user gesture, it blocks it as a pop-up.

You can manually override this via the little Pop-Up modal that shows up on the right-edge of your URL bar:

The interesting thing you brought up is: why does it work from the Console, but not from Snippets? I asked the DevTools team, and one of them informally thinks that DevTools treats Console execution as user gestures, to avoid security checks like these.

One workaround that may be good enough for you is to run your snippet from a new Chrome tab (chrome://newtab). When I run the Snippet from that page, I can open new windows without triggering the "Pop-up blocked" modal.

Thanks for experimenting between how it worked with Console and Snippets. That turned out to be pretty interesting.




回答2:


Indeed, window.open is kind of misleading. This is to the fact that window is the global context in JavaScript and open is a method within that object. You should not read it as "open a window". Actually, it

loads a resource into [...] a new browsing context (such as a window)

(MDN)

Most modern browsers are tabbed, hence a browsing contxt is a tab and, following of that, they (mostly, but not always) would open a new tab rather than a window. What can you do? For example, code like

window.open('http://google.de', 'google', 'width=500,height=500')

actually opens a window for me (Chrome 59). However, it might get blocked as a popup by the browser.



来源:https://stackoverflow.com/questions/45331065/javascript-window-open-works-in-chrome-console-but-not-as-a-snippet

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