无法以编程方式点击<a> tag in Greasemonkey script

时间:2018-03-07 13:25:59

标签: javascript greasemonkey

I'm trying to get Greasemonkey in Firefox to click this anchor which doesn't have an href attribute:

<a class="btn btn-primary pull-right"
   ng-class="{'disabled': programsTabSubmitInProgress}"
   ng-click="handleAddProgramClick()">
  <i class="fa fa-plus"></i>
  <span>Add Program</span>
</a>

I already tried this line of code, but it won't work:

// ==UserScript==
// @name        Final Test
// @description Final test results
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// @include     https://qs-hub.qs.com/#/profiles/topuniversities/programs*
// ==/UserScript==
setTimeout(function () {
  document.querySelector('.btn.btn-primary.pull-right').click();
}, 5000);

Does anyone have the right solution to click this anchor?

1 个答案:

答案 0 :(得分:2)

代码应该可以正常工作。您需要确保单击右侧元素:

console.log(document.querySelector('.btn.btn-primary.pull-right'));

根据评论,您实际上想要点击第五个这样的元素。那就是:

document.querySelectorAll('.btn.btn-primary.pull-right').item(4).click();

document.querySelectorAll返回NodeList,其中clickitem

顺便说一句,你没有使用jQuery,因此不需要在你的脚本中使用它。

请考虑等待页面load

,而不是超时
window.addEventListener('load', function() {
    document.querySelectorAll('.btn.btn-primary.pull-right').item(4).click();
}, false);