为什么内容脚本未检测到事件页面中的以下消息?

时间:2017-07-18 17:08:57

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

我正在尝试使用语法检查API(https://textgears.com/api/)开发语法检查Google Chrome扩展程序。返回的JSON示例是https://api.textgears.com/check.php?text=I+is+an+engeneer!&key=DEMO_KEY

但是,事件页面发送的消息未被内容脚本检测到,并且没有被执行。

扩展的目标:当用户选择页面上的特定文本并单击上下文菜单时,右上角的div元素将显示错误和建议(如果有)。

manifest.json

{
    "manifest_version": 2,
    "name": "GrammarCheck",
    "version": "1.0",
    "description": "To check grammar and style of the text",

    "page_action": {
        "default_title": "Check",
        "default_popup": "popup.html"
    },

    "permissions": [
    "tabs",
    "contextMenus"],

    "content_scripts":[
    {
    "matches": ["*://*/*"],
    "js": ["content.js"],
    "css": ["content.css"]
    }],

    "background": {
    "scripts": ["event.js"],
    "persistent": false
  }
}

event.js

var menu={
    id: "grammar",
    title: "Check Grammar",
    contexts: ["selection"]
}
var num, text;
chrome.contextMenus.create(menu);
chrome.contextMenus.onClicked.addListener(function(click){
    if(click.menuItemId=="grammar" && click.selectionText){
    var url="https://api.textgears.com/check.php?text="+encodeURIComponent(click.selectionText)+"&key=RxOg8C2AsuPygXPN";
    var Httpreq = new XMLHttpRequest(); 
    Httpreq.open("GET",url,false);
    Httpreq.send(null);
    var json_obj = JSON.parse(Httpreq.responseText);
    console.log(json_obj);//json_obj also has the appropriate parameters.
    if(json_obj.result)
    {   chrome.tabs.query({
        currentWindow:true,
        active: true
        }, function(tab){
        console.log("suggest");//suggest gets printed correctly
        tabID=tab[0].id;
        chrome.tabs.sendMessage(tabID,{
        method: "suggest",
        content: JSON.stringify(json_obj)
        });
        });
    }
    else 
    {   
        chrome.tabs.query({
        currentWindow:true,
        active: true
        }, function(tab){
        console.log("error");
        tabID=tab[0].id;
        chrome.tabs.sendMessage(tabID,{
        method: "error",
        content: JSON.stringify(json_obj)
        });
        });
    }
    }
});

content.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    console.log("Entered Content Script");//This is not being printed
    //other statements
});

0 个答案:

没有答案