Jquery 通过chrome扩展弹出窗口填写表格

Jquery 通过chrome扩展弹出窗口填写表格,jquery,google-chrome-extension,browser-action,Jquery,Google Chrome Extension,Browser Action,我想从fill.js加载值,当单击扩展名popup.html中的锚链接时,它将自动填充远程页面上的表单字段,该页面的字段ID为#user+#pw。这是我当前扩展名中的内容,但我不确定清单文件中是否缺少某些内容,或者是否需要back.js fill.js chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) { if (msg.action === "fillFields") { $("#user

我想从fill.js加载值,当单击扩展名popup.html中的锚链接时,它将自动填充远程页面上的表单字段,该页面的字段ID为#user+#pw。这是我当前扩展名中的内容,但我不确定清单文件中是否缺少某些内容,或者是否需要back.js

fill.js

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.action === "fillFields") {
    $("#user").val("name@email.com")
    $("#pw").val("pass123")
}
});
$("#fill").on("click", function(){
chrome.runtime.sendMessage({
    action: 'fillFields'
});
<input name="user" type="text" id="user">
<input name="pw" type="text" id="pw">
popup.js

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.action === "fillFields") {
    $("#user").val("name@email.com")
    $("#pw").val("pass123")
}
});
$("#fill").on("click", function(){
chrome.runtime.sendMessage({
    action: 'fillFields'
});
<input name="user" type="text" id="user">
<input name="pw" type="text" id="pw">
}))

popup.html

<!DOCTYPE html>
<html>
<head>
<title>Autofill</title>
<script src="jquery.js"></script>
<script src="popup.js"></script>
</head>
<a href="#" id="fill">Fill</a>
</body>
</html>
远程表单字段

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
if (msg.action === "fillFields") {
    $("#user").val("name@email.com")
    $("#pw").val("pass123")
}
});
$("#fill").on("click", function(){
chrome.runtime.sendMessage({
    action: 'fillFields'
});
<input name="user" type="text" id="user">
<input name="pw" type="text" id="pw">

您无法从fill.js访问#fill元素,该元素被注入页面(即内容脚本)。弹出窗口在一个范围内运行,内容在另一个范围内运行,背景在另一个范围内运行

在浏览器操作中注入jquery和fill脚本比在清单中加载要好,因为它只在需要时注入,并且在弹出窗口中单击fill时处理程序就准备好了

将此添加到popup.html:

<script src="jquery.js"></script>
<script src="popup.js"></script>
fill.js:

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    if (msg.action === "fillFields") {
        $("#user").val("name@email.com")
        $("#pw").val("pass123")
    }
});

查找在上运行以控制何时注入脚本。您应该没有问题,因为在浏览器操作单击和能够单击填充之间有一个自然延迟。

谢谢!但是我希望能够从弹出菜单中点击一个填充链接(因为我可能有多个值和多个链接),这是可能的吗?填充链接在我回答中的弹出菜单上。要使用多个填充链接,只需发送和回复其他消息,例如,当我单击扩展图标时,Fillfields2不显示html锚定链接说明是将此添加到popup.html: