繁体   English   中英

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

[英]Uncaught TypeError: Cannot read property 'getSelected' of undefined (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});
    });
}

帮助可以带来欢呼

您的脚本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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM