Javascript 通过 Chrome 扩展点击页面上的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26390322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:49:30  来源:igfitidea点击:

Clicking an element on a page through Chrome Extension

javascriptgoogle-chromegoogle-chrome-extensionclick

提问by Rico Clark

I am trying to create a chrome extension that will click on an element on a webpage when you click a button on the extension, but for some reason it does nothing no matter what I try.

我正在尝试创建一个 chrome 扩展程序,当您单击扩展程序上的按钮时,该扩展程序将单击网页上的元素,但由于某种原因,无论我尝试什么,它都无济于事。

I've got this so far

到目前为止我有这个

manifest.json

清单文件.json

{  
  "manifest_version": 2,  

  "name": "Such Activity",  
  "description": "Wow",  
  "version": "1.0",    
  "permissions": [  
        "tabs", "<all_urls>"  
    ],  

  "browser_action": {  
    "default_icon": "icon.png",  
    "default_popup": "popup.html"  
  },  
     "content_scripts": [  
        {  
            "matches": [ "<all_urls>" ],  
           "js": ["content_script.js"]  
            }  
        ]  
}

popup.html

弹出窗口.html

<!doctype html>  
<html>  
  <head>  
    <title>activity</title>  
    <style>  
    </style>  
    <script src="content_script.js"></script>  
  </head>  
  <body>  
  <button id="clickactivity">click</button>  
  </body>  
</html>  

content_script.js

content_script.js

function ClickPlanet()
    {
        var planets = document.getElementsByClassName("planet-name");
        var randomplanet = Math.floor(Math.random() * planets.length);
        var clickplanet = planets[randomplanet];
        clickplanet.click();
        setInterval(function () { ClickPlanet() }, 2000);
    }

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('clickactivity').addEventListener('click', ClickPlanet);
});

All I seem to be getting is this error

我似乎得到的只是这个错误

Uncaught TypeError: Cannot read property 'click' of undefined

I've been fiddling around with this for hours, but I can't get it to work. Any and all help is appreciated!

我一直在摆弄这个好几个小时,但我无法让它工作。任何和所有的帮助表示赞赏!

回答by Marco Bonelli

Issue

问题

Looks like you are misunderstanding the content script's behavior.

看起来您误解了内容脚本的行为。

Quoting the official documentation:

引用官方文档:

Content scripts are JavaScript files that run in the context of web pages. By using the standard Document Object Model (DOM), they can read details of the web pages the browser visits, or make changes to them.

内容脚本是在网页上下文中运行的 JavaScript 文件。通过使用标准的文档对象模型 (DOM),他们可以读取浏览器访问的网页的详细信息,或对其进行更改。

So, using your content_script.jsin your popup.htmldoesn't make much sense, and obviously results in an error because you don't have any button with class="planet-name"in your popup.htmlpage.

因此,在 your使用 your没有多大意义content_script.jspopup.html,并且显然会导致错误,因为您class="planet-name"popup.html页面中没有任何按钮。

Solution

解决方案

To do what you want, you need to create a different script for your popup.html, and add a listener to that button, so when it gets clicked, you can inject the content_script.jsscript into the page to click the "planet" element.

要执行您想要的操作,您需要为您创建一个不同的脚本popup.html,并为该按钮添加一个侦听器,这样当它被点击时,您就可以将content_script.js脚本注入页面以点击“行星”元素。

So you'll have to:

所以你必须:

  1. Edit your manifest.jsonremoving the "content_scripts"field
  2. Create a popup.jsfile to add in your popup.htmlpage
  3. Add a listener for the button click inside popup.jsto inject the content_script.jsfile using chrome.tabs.executeScript()
  4. Edit your content_script.jsto make it click the button directly on the page
  1. 编辑您的manifest.json删除"content_scripts"字段
  2. 创建popup.js要添加到popup.html页面中的文件
  3. 为按钮单击添加一个侦听器以使用popup.js注入content_script.js文件chrome.tabs.executeScript()
  4. 编辑您的content_script.js以使其直接单击页面上的按钮


  1. First of all, edit your manifest.json, it should look like this:

    {  
        "manifest_version": 2,  
    
        "name": "Such Activity",  
        "description": "Wow",  
        "version": "1.0",    
        "permissions": ["tabs", "<all_urls>"],  
    
        "browser_action": {  
            "default_icon": "icon.png",  
            "default_popup": "popup.html"  
        }
    }
    
  2. Then, remove your content_script.jsfrom the popup.htmland replace it with the popup.jsscript:

    <!doctype html>  
    <html>  
        <head><title>activity</title></head>  
    <body>  
        <button id="clickactivity">click</button>  
        <script src="popup.js"></script> 
    </body>
    </html>  
    
  3. Create the popup.jsscriptand add the listener to the button that will inject the script into the current page:

    function injectTheScript() {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            // query the active tab, which will be only one tab
            //and inject the script in it
            chrome.tabs.executeScript(tabs[0].id, {file: "content_script.js"});
        });
    }
    
    document.getElementById('clickactivity').addEventListener('click', injectTheScript);
    
  4. Now, in your content_script.js, you'll need to click the button directly, and also you will not need to use DOMContentReady, because Chrome waits to inject the script by itself. So, your new content_script.jswill be:

    function clickPlanet() {
        var planets = document.getElementsByClassName("planet-name"),
            randomplanet = Math.floor(Math.random() * planets.length),
            clickplanet = planets[randomplanet];
    
        clickplanet.click();
    }
    
    clickPlanet();
    
  1. 首先,编辑你的manifest.json,它应该是这样的

    {  
        "manifest_version": 2,  
    
        "name": "Such Activity",  
        "description": "Wow",  
        "version": "1.0",    
        "permissions": ["tabs", "<all_urls>"],  
    
        "browser_action": {  
            "default_icon": "icon.png",  
            "default_popup": "popup.html"  
        }
    }
    
  2. 然后,从 中删除您content_script.jspopup.html并将其替换为popup.js脚本

    <!doctype html>  
    <html>  
        <head><title>activity</title></head>  
    <body>  
        <button id="clickactivity">click</button>  
        <script src="popup.js"></script> 
    </body>
    </html>  
    
  3. 创建popup.js脚本并将侦听器添加到将脚本注入当前页面的按钮:

    function injectTheScript() {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            // query the active tab, which will be only one tab
            //and inject the script in it
            chrome.tabs.executeScript(tabs[0].id, {file: "content_script.js"});
        });
    }
    
    document.getElementById('clickactivity').addEventListener('click', injectTheScript);
    
  4. 现在,在您的 中content_script.js,您需要直接单击按钮,而且您也不需要使用DOMContentReady,因为 Chrome 会等待自己注入脚本。所以,你的新content_script.js将是:

    function clickPlanet() {
        var planets = document.getElementsByClassName("planet-name"),
            randomplanet = Math.floor(Math.random() * planets.length),
            clickplanet = planets[randomplanet];
    
        clickplanet.click();
    }
    
    clickPlanet();
    

Working example

工作示例

Download a working example of the extension from HERE.

这里下载扩展的工作示例。

Documentation

文档

I strongly suggest you to take a look at the documentationfor the methods used in my example to fully understand their behavior and their properties, here are some links you may find useful:

我强烈建议您查看我的示例中使用的方法的文档,以充分了解它们的行为和属性,以下是您可能会发现有用的一些链接: