Google Chrome扩展错误

时间:2014-06-30 12:57:43

标签: google-chrome google-chrome-extension

chrome-extension,遇到错误

Uncaught TypeError: Cannot read property 'sendRequest' of undefined

这是我的代码

的manifest.json

{
  "manifest_version": 2,
  "name": "blah",
  "version": "1.0",
  "description": "blah",
  "browser_action": {
    "default_icon": "icon.png"

    },
  "background": "bg.html", // change to your background page
  "permissions": ["http://*/*", "tabs"], //need permission to access all pages & tabs
   "content_scripts": [
   {
     "matches": ["http://*/*", "https://*/*"], // run for http & https pages
     "js": ["key_event.js"],  // key_event.js is injected to the page, this handles key press
     "run_at": "document_start" // run before everything else, else there will be conflicts at pages which accept keyboard inputs ( eg:google search)
   }
   ]
}

key_event.js

if (window == top) {
window.addEventListener('keyup', doKeyPress, false); //add the keyboard handler
}


function doKeyPress(e){
     if (e.keyCode == 17){ // if e.shiftKey is not provided then script will run at all instances of typing "G"
         alert("pressed");

        chrome.extension.sendRequest({redirect: "https://www.google.co.in"});//build newurl as per viewtext URL generated earlier.
     }
}

bg.html

chrome.extension.onRequest.addListener(function(request, sender) {
        chrome.tabs.update(sender.tab.id, {url: request.redirect});
    });

请帮帮我

1 个答案:

答案 0 :(得分:2)

正如评论中已经提到的那样

  • 清单版本2的background部分必须类似于

    "background": {"scripts": ["bg.js"]}
    

没有后台页面,只有后台脚本。因此,您必须将代码从bg.html移至bg.js并从中删除所有额外的HTML。

  • chrome.extension.sendRequestchrome.extension.onRequest已被弃用,分别支持chrome.runtime.sendMessagechrome.runtime.onMessage。这意味着,您仍然可以使用sendRequestonRequest,但可能会在将来的Chrome版本中删除
  • G的keyCode是71而不是17