我试图在 chrome 扩展中创建一个 js 函数,该函数应该有一个字符串作为参数,并将该字符串的每个字母替换为特定的字符,如果您将参数传递为:'con("string is这里”);' ,但如果通为包含它不喜欢的工作字符串VAR:con(varThatHasString);
镀铬控制台错误:Uncaught TypeError: Cannot read property 'split' of undefined at con
,
我的js:
var letters = [
'q','ض',
'w','ص',
'e','ث',
'r','ق',
't','ف',
'y','غ',
'u','ع',
'i','ه',
'o','خ',
'p','ح',
'a','ش',
's','س',
'd','ي',
'f','ب',
'g','ل',
'h','ا',
'j','ت',
'k','ن',
'l','م',
'z','ئ',
'x','ء',
'c','ؤ',
'v','ر',
'b','لا',
'n','ى',
'm','ة',
'[','ج',
']','د',
';','ك',
',','و',
'.','ز',
'/','ظ',
"'",'ط',
' ',' ',
'1','1',
'2','2',
'3','3',
'4','4',
'5','5',
'6','6',
'7','7',
'8','8',
'9','9',
'0','0'
];//all the used charchters
var lastSelect;// last selected text from page
function con(english) {//convert from english to arabic
var aoutput = new Array;
var chars = english.split('');
for(var i=0;i < chars.length;i++){
aoutput.push(letters[letters.indexOf(chars[i])+1]);
}
var ar = aoutput.join();
var res = ar.replace(/,/g,'');
document.getElementById('copy_box').value = res;
return res;
}
//code will run only when there is text already selected on page
chrome.tabs.executeScript( null, {code:"window.getSelection().toString();"}, function(results){
lastSelect = results[0];
});
con(last_select);
当我运行扩展程序时,它只是在文本字段中不显示任何内容,但是当我转到控制台并尝试该功能本身时,它运行良好,并尝试con(last_select);
运行良好并在文本字段中显示输出
没有理由string
不能将变量传递到您的con()
函数中。如果你是在传递什么比其他undefined
(甚至null
),它会抛出一个TypeError
。因此,您传递的变量必须不正确undefined
。
确保您传入的任何变量都不是未定义的,并且您的函数将正常工作。
编辑:
既然您已经包含了代码,@wOxxOm 的评论就是真正的答案;问题是这chrome.tabs.executeScript
是异步的,所以你在设置con(last_select)
之前调用last_select
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句