【问题标题】:Automatically Type In Current Tab Search Bar-Chrome Extensions自动输入当前标签搜索栏-Chrome 扩展
【发布时间】:2020-02-12 04:24:28
【问题描述】:

我只是学习 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 上)更新为将“守望先锋”作为其值或显示在 youtube 页面中。

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension


    【解决方案1】:

    您需要找到搜索栏的 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*/ + '";'}
      );
    });
    

    希望对你有帮助

    【讨论】:

    • 所以 /*you value*/ 将是我想要输入的值,例如 'JavaScript Tutorials' ?此外,这非常有帮助。谢谢!
    • 现在想想,当我运行脚本时,是否需要点击搜索才能开始搜索?还是自动完成?
    • 这取决于您的代码。如果你想要那个自动的。确保代码在页面加载后运行。
    • 现在出现权限错误。知道如何解决吗?未选中 runtime.lastError:无法访问页面内容。扩展清单必须请求访问相应主机的权限。编辑:我通过在清单中添加“activeTab”来修复权限
    • manifest.json 文件中添加要访问权限密钥的 url 页面
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多