弹出窗口中的一组链接,用设置的文本填充特定命名的字段

Set of links in popup to populate a specifically named field with set text

本文关键字:填充 文本 设置 字段 链接 窗口 一组      更新时间:2023-09-26

我不喜欢创建扩展,我花了一整天的时间在这上面,我完全不知道我要做什么。

有没有可能在chrome扩展弹出窗口中有一组链接,这些链接具有onclick代码来填充特定名称的表单字段,并在光标所在的位置放置特定的文本?

例如,我希望它以"电子邮件"字段为目标,并在其中填充"joe@joebloggs.com"但我不希望这是可定制的。此外,输入字段名称是电子邮件,并且没有id,所以我会尝试使用吗?"

getelementsbyname

那里没有快乐。

对于此任务,您需要使用onMessage、sendMessage和query。onMessage是chrome的一种方法。runtime、sendMessagequery都是选项卡的方法。

清单

您要做的第一件事是将选项卡权限添加到清单文件中。

"permissions": [
    "tabs"
],

弹出HTML

对于弹出页面,您需要将Javascript与html页面分离。您不能再将内联Javascript添加到弹出页面。因此,创建一个HTML和Javascript文件。对于这个例子,我将通过给它一个ID来使用锚标记。点击它将触发数据的发送。

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Popup</title>
</head>
<body>
    <div id="mainPopup">
        <h1>Popup</h1>
        <p>
            <a href="#" id="email-filler">Email</a>
        </p>
    </div>
    <script src="popup.js"></script>
</body>
</html>

弹出式Javascript

现在,当单击锚标记时,会触发onClick事件,并将数据发送到内容脚本。

// tab options
var tabOptions = {
    active: true,
    currentWindow: true
};
// when button is clicked
document.getElementById("email-filler").onclick = function () {
    // we use tabs query to find the id of the tab you wish to send data to
    chrome.tabs.query(tabOptions, function (tab) {
        // parameter 1: id of the tab you are sending data to
        // parameter 2: the data you are sending to the tab
        chrome.tabs.sendMessage(tab[0].id, "joe@joebloggs.com");
    });
};

内容脚本

最后,将以下内容添加到您的内容脚本中。请求变量包含您从弹出页面发送的数据。

chrome.runtime.onMessage.addListener(onRequest);
function onRequest(request, sender, sendResponse) {
    console.log(request);
    document.getElementsByName("SOME-NAME")[0].value = request;
}