jQuery .trigger('click')无效

时间:2014-10-31 05:13:11

标签: jquery google-chrome google-chrome-extension userscripts tampermonkey

这个代码段可以与TamperMonkey一起使用,但是当我尝试在Chrome扩展程序中使用它时,它没有做任何事情,我做错了什么?

我想在XenForo论坛上喜欢我的每一篇文章。

$('li[data-author="TesoMayn"]').each(function() {
    $("a.LikeLink").trigger("click");
});

更多信息:

的manifest.json:

{
"background": {
    "persistent": true,
    "scripts": [
        "jquery.min.js",
        "autolike.js",
        "autolike.min.css"
    ]
},
"content_scripts": [
    {
        "js": [
            "jquery.min.js",
            "autolike.js"
        ],
        "css": [
            "autolike.min.css"
        ],
        "matches": [
            "http://domain.com/*",
            "https://domain.com/*"
        ],
        "run_at": "document_start"
    }
],
"web_accessible_resources": [
    "jquery.min.css",
    "autolike.js",
    "autolike.min.css"
],
"description": "Autolike My Post",
"manifest_version": 2,
"name": "Autolike",
"permissions": [
    "http://domain.com/",
    "https://domain.com/",
    "cookies",
    "alarms",
    "notifications"
],
"update_url": "https://clients2.google.com/service/update2/crx",
"version": "1.7.5"
}

autolike.js

$(document).ready(function() {
  var css = chrome.extension.getURL('autolike.min.css');
  $("head").append('<link href="'+ css +'" rel="stylesheet" type="text/css" />');
  $('li[data-author="TesoMayn"]').each(function() {
      $('a.LikeLink').trigger('click');
  });
});

1 个答案:

答案 0 :(得分:2)

尝试createEvent而不是触发器()。这模拟了一次咔嗒声,就像用鼠标点击一样。

$('li[data-author="TesoMayn"] a.LikeLink').each(function() {
    var event = document.createEvent("MouseEvent");
    event.initMouseEvent("click", true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
    this.dispatchEvent(event);
});