admin管理员组

文章数量:1391964

This code:

a = document.createElement('a')
a.setAttribute('href','')
a.click()

works in chrome. It open www.google.de as expected. But in firefox it does nothing. Why and how can it be made to work?

I am using firefox 40.0.3 on ubuntu linux 15.04.

This code:

a = document.createElement('a')
a.setAttribute('href','http://www.google.de')
a.click()

works in chrome. It open www.google.de as expected. But in firefox it does nothing. Why and how can it be made to work?

I am using firefox 40.0.3 on ubuntu linux 15.04.

Share Improve this question edited Aug 29, 2015 at 12:15 Nathan asked Aug 29, 2015 at 12:12 NathanNathan 7,75914 gold badges74 silver badges150 bronze badges 3
  • Do you ever actually add the newly created anchor element to the page DOM? – Nathan Commented Aug 29, 2015 at 12:14
  • No, I don't. I want this to happen in the background and not appear on the page. – Nathan Commented Aug 29, 2015 at 12:16
  • 2 It seems that firefox won't execute the click event when the element not attached to the body – SVK Commented Aug 29, 2015 at 12:20
Add a ment  | 

2 Answers 2

Reset to default 7

Use the following:

var a = document.createElement('a')
a.setAttribute('href','http://www.google.de');
document.getElementsByTagName('body')[0].appendChild(a);
a.click();

Firefox probably doesn't open the link because you never add it to the DOM.

You could add the element to the DOM and use css display:none to hide it from the page.

However, a more standard approach would be to either use the javascript window.open() method or window.location.href depending on your desired behavior.

本文标签: javascriptanchors click function not working in firefoxStack Overflow