我正在开发一个chrome扩展程序,我希望它能够由用户获取所选文本,当我在类似的非扩展页面上运行代码时,代码工作正常,但它在我的后台页面扩展中不起作用。即使我试图在console.log中获取选择的值,它也不会返回任何内容。这是我的javascipt文件:
window.onload = myOnload;
function myOnload(){
var button = document.getElementById("button");
chrome.contextMenus.create({
"title":"MissLang Fix",
"contexts":["all"],
"onclick": myClick2
});
document.getElementById("input").innerHTML = "mojtaba";
button.onclick= function(){myClick()};
}
function myClick2(){
var txt = '';
if (chrome.extension.getBackgroundPage().window.getSelection)
txt = chrome.extension.getBackgroundPage().window.getSelection();
else if (chrome.extension.getBackgroundPage().document.getSelection)
txt = chrome.extension.getBackgroundPage().document.getSelection();
else if (chrome.extension.getBackgroundPage().document.selection)
txt = chrome.extension.getBackgroundPage().document.selection.createRange().text;
console.log("this is the console message");
console.log("txt: " + txt);
}
function myClick(){
var myString = document.getElementById("input").value;
for(var i=0;i<myString.length;i++){
myString = myString.replace("q","ض");
myString = myString.replace("w","ص");
}
document.getElementById("output").innerHTML = myString;
}
这是我的manifest.json文件:
{
"name": "MissLang Fix extension",
"manifest_version": 2,
"version": "1.0",
"description": "fixing english to farsi typings.",
"icons":{
"16":"icon_16.png",
"128":"icon_128.png"
},
"background":{
"scripts":["script.js"]
},
"browser_action": {
"default_icon": "icon.png",
"default_popup": "missLangFix.html"
},
"permissions": [
"tabs",
"contextMenus"
]
}