gpt4 book ai didi

javascript - 使用 Chrome 扩展中的消息传递处理 keyup 事件

转载 作者:行者123 更新时间:2023-11-28 03:55:51 24 4
gpt4 key购买 nike

我是 Chrome 扩展开发新手。我正在尝试创建一个由文本字段和按钮组成的扩展。如果用户在文本字段中输入一些文本,那么确切的内容应该自动输入 HTML 页面的登录 ID 字段。

这是我的文件..

弹出.html

<!doctype html>
<!--
This page is shown when the extension button is clicked, because the
"browser_action" field in manifest.json contains the "default_popup" key
with
value "popup.html".
-->
<html>
<head>
<title>Email Extension</title>
<script type="text/javascript" src="popup.js"></script>
</head>

<body>
<center>
Enter email id:
<br>
<br>
<input type="text" id="txtEmail">
<br>
<br>
<input type="button" id="btnClear" value=" Clear ">
</center>
</body>
</html>

Popup.js

 document.addEventListener('DOMContentLoaded', function() {
var btnElement = document.getElementById("btnClear");
var txtElement = document.getElementById("txtEmail");
// onClick's logic below:
btnElement.addEventListener('click', function() {
clearField();
});

txtElement.addEventListener('keyup', function() {
changeEmail();
});

function clearField() {
txtElement.value = "";
}

function changeEmail() {
var emailId = txtElement.value;
chrome.runtime.sendMessage({msg:emailId}, function(response) {
console.log("written");
});
}
});

list .json

{
"manifest_version": 2,

"name": "Email Extension",
"description": "This extension allows the user to enter Email id for login.",
"version": "1.0",

"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "Click to Enter user id"
},

"permissions": [
"activeTab",
"storage"
],

"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["myscript.js"]
}
]
}

myscript.js

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse){
var email = document.getElementById("login_username");
email.value = request.msg;
console.log(request);
console.log(sender);
console.log(email.value);
}
);

它只是在控制台上显示“书面”。不在控制台显示请求、发件人内容,也不在 login_username

中输入任何内容

有人可以帮忙找出我哪里出了问题吗?

最佳答案

您无法使用 chrome.runtime.sendMessage 向内容脚本发送消息。您必须将 chrome.tabs.sendMessage 与运行内容脚本的选项卡的 ID 结合使用。例如,要将其发送到当前事件的选项卡,您可以使用类似以下内容的内容:

function changeEmail(){
var emailId = txtElement.value;
chrome.tabs.query({active:true,currentWindow:true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id,{msg:emailId}, function(response) {
console.log("written");
});
});
}

关于javascript - 使用 Chrome 扩展中的消息传递处理 keyup 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47543478/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com