search

Home  >  Q&A  >  body text

Difference between a.click() in Firefox and Google

code show as below

<!-- test.html -->
<button>Click</button>
//test.js
var btn = document.querySelector('button')
btn.onclick = () => {
    var a = document.createElement('a')
    a.href = 'https://www.baidu.com'
    a.target = '_blank'
    a.click()
}

Questions are as follows:

There is no response when clicking the button in Firefox, but you can create a new tab page by clicking the button in Google;
Add a statement to test.js

var btn = document.querySelector('button')
btn.onclick = () => {
    var a = document.createElement('a')
    a.href = 'https://www.baidu.com'
    a.target = '_blank'
    
    document.body.appendChild(a)
    
    a.click()
}

The rewritten code can run normally in both browsers. So I would like to ask my friends what is the reason for this, thank you?

巴扎黑巴扎黑2761 days ago912

reply all(2)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-07-05 11:03:11

    Owner, didn’t you execute the click event just after you created it before adding it to the page?

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-07-05 11:03:11

    The browser will parse the difference
    But if you want to click a button to access the webpage, you can just use window.open or location.assign. Why do you need to create a dom?

    reply
    0
  • Cancelreply