代码之家  ›  专栏  ›  技术社区  ›  Stove Games Games

自动键入当前选项卡搜索栏Chrome扩展程序

  •  0
  • Stove Games Games  · 技术社区  · 5 年前

    我只是在学习JavaScript,主要是为了在特定网站上自动搜索,并比较从这些搜索中收集的一些数据。因此,我想知道是否有可能在我想创建的chrome扩展中使用JavaScript在该网站的搜索栏上做这样的事情。

    注意:网站中的搜索栏示例如下 YouTube's 搜索栏

    编辑:经过更深入的研究,我发现 forum.submit 可能有用,但我不太确定。

    编辑2:

    extension_ui.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>extension_ui</title>
    </head>
    <body>
        <button>Start</button>
        <script src="find_time_slots.js" charset="utf-8"></script>
    </body>
    </hmtl>
    

    find_time_slots.js

    document.addEventListener('DOMContentLoaded', function(){
        document.querySelector('button').addEventListener('click',onclick,false)
    
        function onclick(res){
            chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
              chrome.tabs.executeScript(
                res.tabNum,
                {code: 'document.getElementById("search").value = "overwatch";'}
              );
            })
        }
    
    },false)
    

    content.js

    chrome.runtime.onMessage.addListener(function(request,sender,sendResponse){
        sendResponse({tabNum: sender.id})
    });
    

    虽然我没有收到任何错误,但它不会将搜索栏(在youtube上)更新为“overwatch”作为其值或显示在youtube页面上。

    0 回复  |  直到 5 年前
        1
  •  -1
  •   Iván Nokonoko    5 年前

    您需要找到搜索栏的id。在youtube上,id是 search ;

    在popup.js中使用 chrome.tabs.executeScript 而且它需要放在一个监听器事件中。

    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.executeScript(
        tabs[0].id,
        {code: 'document.getElementById("search").value = "' + /*you value*/ + '";'}
      );
    });
    

    希望这能对你有所帮助