您好,我正在制作 google chrome 扩展程序并遇到错误
Uncaught TypeError: Cannot read property 'getSelected' of undefined
我的代码如下
调用函数 getQueryString();在 if 语句中产生错误
key_event.js
if (window == top) {
window.addEventListener('keyup', doKeyPress, false); //add the keyboard handler
}
trigger_key = 37;
function doKeyPress(e){
if (e.ctrlKey && e.keyCode == 37)
{
alert("leftpressed");
getQueryString();
}
else if(e.ctrlKey && e.keyCode == 39){ // if e.shiftKey is not provided then script will run at all instances of typing "G"
alert("rightpressed");
getQueryString();
}
}
function getParameterByName(name,urlPara) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(urlPara);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function getQueryString() {
chrome.tabs.getSelected(null, function(tab) {
var tab = tab.url;
var queryString = {};
var substr = tab.replace(
new RegExp("([^?=&]+)(=([^&]*))?", "g"),
function($0, $1, $2, $3) { queryString[$1] = $3; }
);
var current = getParameterByName('page',tab);
var reExp = 'page=' + current;
current = parseInt(current, 10)-1;
var newUrl = tab.replace(reExp, 'page=' + current);
console.log(newUrl);
chrome.runtime.sendMessage({redirect: newUrl});
});
}
帮助可以带来欢呼
最佳答案
您的脚本 key_event.js
是一个内容脚本。它在网站上下文中运行,而不是在扩展上下文中运行。因此,它无法使用所有 chrome
API(如 chrome.tabs
)。
为了从网站上下文中获取当前网站 URL,您可以使用 window.location.href
。您还可以使用 window.location.search
获取查询字符串。所以这里不需要查询chrome.tabs
。
行内的事
var tabURL = window.location.href;
var queryString = window.location.search;
关于javascript - 未捕获的类型错误 : Cannot read property 'getSelected' of undefined (Chrome-Extension ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24526112/