【问题标题】:Uncaught TypeError: Cannot read property 'getSelected' of undefined (Chrome-Extension )未捕获的类型错误:无法读取未定义的属性“getSelected”(Chrome-Extension)
【发布时间】:2014-07-02 08:14:12
【问题描述】:

您好,我正在制作 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});
    });
}

帮助可以带来欢呼

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • popup.html 来自哪里?我们是否在谈论相同的扩展名,因为上面提到的清单中没有 popup.html。您的问题是关于内容脚本中的错误,因此不应该涉及 popup.html
    • 当使用“window.location.href”时,我得到了扩展的路径:“CHROME-EXTENSION://” - 为什么?
    猜你喜欢
    • 1970-01-01
    • 2021-12-22
    • 2015-01-06
    • 2017-07-26
    • 2021-06-07
    • 2019-02-26
    • 2017-11-02
    相关资源
    最近更新 更多