我是一个创建扩展程序的菜鸟,而且我整天都花在这上面,而且我完全无处可寻。
是否可以在chrome扩展程序弹出窗口中设置一组链接,这些链接具有onclick代码以填充特定命名的表单字段,并在光标所在的位置放置特定的文本位?
例如,我希望它定位"电子邮件"字段并填入" joe@joebloggs.com"但我不希望这是可定制的。输入字段名称也是电子邮件,它没有ID,所以我会尝试使用
getelementsbyname
没有欢乐。
答案 0 :(得分:2)
要完成此任务,您需要使用onMessage,sendMessage和query。 onMessage
是一种chrome.runtime,sendMessage
,query
的方法,都是tabs的方法。
<强>清单强>
您要做的第一件事是将标签权限添加到manifest文件。
"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;
}