未捕获的TypeError:无法读取未定义的属性“getSelected”(Chrome-Extension)

时间:2014-07-02 08:14:12

标签: javascript google-chrome google-chrome-extension

您好我正在制作谷歌浏览器扩展程序并且错误

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});
    });
}

帮助可以带来欢呼

1 个答案:

答案 0 :(得分:5)

您的脚本key_event.js是一个内容脚本。它在网站的上下文中运行,而不是在扩展上下文中运行。因此,它无法使用所有chrome API(例如chrome.tabs)。

要从网站上下文中获取当前网站网址,您可以使用window.location.href。您还可以使用window.location.search获取查询字符串。因此,无需在此处查询chrome.tabs

中的某些内容
var tabURL = window.location.href;
var queryString = window.location.search;