简体   繁体   中英

setAttribute target _blank doesn't open in new tab

var a = document.createElement('a');
a.setAttribute('target','_blank');
a.click();

The above code doesn't work for me. Does setAttribute not work if the click event happens in JavaScript ?

Anchor elements without href attributes aren't linking to anywhere, so they aren't links, so clicking on one doesn't do anything .

When I added setAttribute("href", "something") it triggered a new window in my test.

IF you also set an href attribute

a.setAttribute('href','https://google.com')

Then when you call a.click() what you will most likely see (in Chrome and Canary) is that the browser will block this popup. This is due to the fact that this is pretty much textbook annoying popup, and since the click was not initiated at first by a click from the user, it is seen as spammy.

If you need to do this, it will usually work if you are triggering the inner "click" from a user initiated (onclick) event handler of some type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM