问题描述
当试图关注文本字段(输入或文本区域)时,我尝试使用chrome扩展名来动态添加按钮.想法是单击按钮,以按需输入à字符串来填充文本字段.
I'm trying to use a chrome extension to dynamically add a button when focusing on a text field (input or text area). the idea would be to click on the button to fill the text field with à string on demand.
我找到了一些代码来添加按钮,但是"onclick"不起作用.您将看到,我有多种触发控制台日志的方法,但没有一种有效.我找不到实现此目的的方法,因此我要求有关实现此方法的一些指导.
I found a bit of code to add up the button but the "onclick" doesn't work.You will see that I have many ways to trigger console log but none works.I can't find a way to make this work so I ask for some guidance regarding the way to achieve this.
清单
{
"name": "-",
"description": "-",
"version": "0.1",
"permissions": [
"tabs","<all_urls>"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"js": ["content.js"]
}
],
"background" : { "scripts": ["background.js"] },
"manifest_version": 2
}
内容脚本
var btn = createButton();
document.addEventListener('focusin', onFocusIn);
var el;
function onFocusIn(event) {
el = event.target;
if (el.contentEditable ||
el.matches('input, textarea') && el.type.match(/email|number|search|text|url/))
{
appendButton(el);
}
}
function createButton() {
var btn = document.createElement('button');
btn.textContent = 'Yay!';
btn.id = "explicite";
console.log(btn);
//not working
btn.onclick = function(event) {
btn.textContent += '!';
};
//not working
btn.setAttribute("onClick", "alert('OnClick')");
return btn;
}
function appendButton(textElement) {
textElement.parentElement.insertBefore(btn, textElement.nextElementSibling);
//not working
document.getElementById("explicite").addEventListener('click', function() {
alert("HI");
});
}
推荐答案
问题出在您的onFocusIn
代码document.addEventListener('focusin', onFocusIn);
中.您将onFocusIn
附加在文档中的所有元素上.因为,按钮也是在其上执行的可聚焦元素onFocusIn
代码.
The problem is in your onFocusIn
code document.addEventListener('focusin', onFocusIn);
. You are attaching onFocusIn
on all elements in the documents. Since, a button is also an focusable element onFocusIn
code executing on that as well.
一个简单的解决方案是:
Simple solution for that is :
function onFocusIn(event) {
el = event.target;
if(el.type != "button" && el.type != "submit" ) {
if (el.contentEditable ||
el.matches('input, textarea') && el.type.match(/email|number|search|text|url/))
{
appendButton(el);
}
}
}
您可能想要更改document.addEventListener('focusin', onFocusIn);
事件代码或调整绑定的功能.
You may want to change the document.addEventListener('focusin', onFocusIn);
event code or adjust the binded function.
希望这会有所帮助!
这篇关于使用扩展名将按钮添加到文本字段-不可点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!