我正在尝试创建一个Chrome扩展程序,在输入字段上执行自动填充功能。
首先,请查看普通HTML页面上的功能代码
<!DOCTYPE html>
<html>
<head>
<title>Testing autocomplete</title>
<script>
var people = ['Fabio', 'Marco', 'Pietro', 'Kucio', 'Pato'];
function matchPeople(input) {
var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
return people.filter(function(person) {
if (person.match(reg)) {
return person;
}
});
}
function changeInput(val) {
var autoCompleteResult = matchPeople(val);
var text = "";
var i;
for (i = 0; i < autoCompleteResult.length; i++) {
text += autoCompleteResult[i] + "<br>";
}
document.getElementById("result").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" onkeyup="changeInput(this.value)">
<div id="result"></div>
</body>
</html>
现在,如果我们在任何网页上运行此代码,它就可以了。
我遇到的问题是在Chrome扩展程序中移动上述功能。
我的 manifest.json 在这里:
{
"name": "AutoComplete UZ",
"version": "1.0",
"description": "Provides with a small popup window with the AutoComplete function with UZ internal emails.",
"browser_action": {
"default_popup": "popup.html",
"default_title": "UZ AutoComplete"
},
"content_scripts": [
{
"matches" : ["http://*/*", "https://*/*"],
"css": ["style.css"],
"js" : ["popup.js"]
}
],
"manifest_version": 2
}
我的 popup.html 文件:
<!DOCTYPE html>
<html>
<head>
<title>UZ AutoComplete</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="popup.js"></script>
</head>
<body>
<h1>UZ AutoComplete</h1>
<h3>Type email address</h3>
<input id="amount" type="text" onkeyup="changeInput(this.value)" placeholder="your email">
<div id="result"></div>
</body>
</html>
和我的 popup.js 文件在这里:
var people = [
'Fabio',
'Marco',
'Pietro',
'Kucio',
'Pato'
];
function matchPeople(input) {
var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
return people.filter(function(person) {
if (person.match(reg)) {
return person;
}
});
}
function changeInput(val) {
var autoCompleteResult = matchPeople(val);
var text = "";
var i;
for (i = 0; i < autoCompleteResult.length; i++) {
text += autoCompleteResult[i] + "<br>";
}
document.getElementById("result").innerHTML = text;
}
如果我打包上述文件并创建扩展名,则上述代码将无法使用。我看到了popup.html输入字段,但是使得魔法的功能不会触发,我不明白为什么。
我认为我不需要一个event.js页面来运行上述简单的功能,但请告诉我最好的方法。希望我对我想要实现的目标足够清楚。
任何帮助都不仅仅是欢迎stackoverflowers!
答案 0 :(得分:1)
Google Chrome扩展程序do not allow inline Javascript。
您需要在popup.js
中添加一个事件监听器。
document.querySelector('#amount').addEventListener('keyup', function() {
//get input's value and call your functions here
});