I am trying to make a chrome extension that replaces the last word typed in the current <textarea>one when the user makes some kind of fire keydown. So I tried this, but it really doesn't work.
Here are the files of my extension:
My extension manifest.json:
{
"name": "Test",
"description": "test",
"version": "0.0.1",
"permissions": [
"activeTab"
],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_title": "replace test"
},
"manifest_version": 2
}
His background.js:
chrome.tabs.executeScript(null, {file: "content_script.js"});
And him content_script.js:
document.onkeydown = replacePrevWord;
function KeyPress(e) {
var evtobj = window.event? event : e
if (evtobj.keyCode == 222 && evtobj.ctrlKey)
return true;
}
function getCaretPosition(ctrl) {
var CaretPos = 0;
if (document.selection) {
ctrl.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
function returnWord(text, caretPos) {
var index = text.indexOf(caretPos);
var preText = text.substring(0, caretPos);
if (preText.indexOf(" ") > 0) {
var words = preText.split(" ");
return words[words.length - 1];
}
else {
return preText;
}
}
function replacePrevWord() {
if(KeyPress()){
var text = document.activeElement;
var caretPos = getCaretPosition(text)
var word = returnWord(text.value, caretPos);
if (word != null) {
text.value = text.value.replace(word,"replaced");
}
}
}
This works fine on JSFiddle ( http://jsfiddle.net/cyo646cr/3/ ), but I don't know how to do this in the Chrome extension.
Any ideas?
Thank.
source
share