首页 > 解决方案 > 谷歌扩展如何点击网页上的按钮?

问题描述

我创建了一个扩展文件github.js

jQuery(document).ready(function($) {
  console.log('github.js');
  // btn btn-primary shelf-cta
  var button = $('.btn.btn-primary.shelf-cta');
  console.log('button.html() = ', button.html());
  button.click();
});

文件 popup.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <button id="send_messages">Send Messages</button>

  <script src="libs/jquery-v3.3.1.js"></script>
  <script src="popup.js"></script>
</body>
</html>

文件弹出.js

jQuery(document).ready(function($) {
  console.log('popup.js');

  $('#send_messages').click(function(event) {


    console.log('github test');
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
      chrome.tabs.executeScript(
        tabs[0].id,
        {file: "libs/jquery-v3.3.1.js"},
        function(){
          chrome.tabs.executeScript(
            tabs[0].id,
            {file: "github.js"}
          );
        }
      );
    });
  });
});

文件清单.json

{
  "name": "test the extension",
  "version": "1.0",
  "description": "Automatically send the message to the opened projects in the browser",
  "permissions": [
    "tabs", 
    "activeTab", 
    "declarativeContent", 
    "storage",
    "<all_urls>"
  ],
  "options_page": "options.html",
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "images/get_started16.png",
      "32": "images/get_started32.png",
      "48": "images/get_started48.png",
      "128": "images/get_started128.png"
    }
  },
  "icons": {
    "16": "images/get_started16.png",
    "32": "images/get_started32.png",
    "48": "images/get_started48.png",
    "128": "images/get_started128.png"
  },
  "manifest_version": 2
}

当我去 github 页面https://github.com/ 有一个“阅读指南”按钮,我想点击它。我按下扩展 browser_action 按钮,显示一个弹出窗口。当我按下按钮“发送消息”时,什么也没有发生。我可以到达“阅读指南”按钮并输出标题但button.click(); 不起作用。如何点击按钮或其他链接?

标签: javascriptgoogle-chrome-extension

解决方案


所以jquery中的点击需要使用这段代码来完成

button.get(0).click();

不像我那样

button.click();

推荐阅读