没有从网页接收任何数据到chrome扩展名的content.js

时间:2012-11-30 01:30:14

标签: google-chrome-extension

我正试图通过按钮点击发送消息,甚至在我的网站上也可以通过Chrome扩展程序在标签中打开。

但是,我无法从网页上收到任何消息,而且我收到端口错误。

我的内容.js:

var port = chrome.extension.connect();

port.onMessage.addEventListener("message", function(event) {
    // We only accept messages from ourselves
    if (event.source != window)
      return;

    if (event.data.type && (event.data.type == "FROM_PAGE")) {
      console.log("Content script received: " + event.data.text);
      port.postMessage(event.data.text);
    }
}, false);


chrome.tabs.onMessage.addListener(function(tabId, changeInfo, tab) {
  alert(changeInfo);
}); 

Popup.js

    $("#linkify").click(function() {
        chrome.tabs.create({
            'url': 'http://localhost:3000/signin'
        }, function(tab) {
            // Tab opened.
            chrome.tabs.executeScript(tab.id, {
                file: "jquery.js"
            }, function() {
                console.log('all injected');
                chrome.tabs.executeScript(tab.id, {
                    file: "content.js"
                }, function() {
                    console.log('all injected');
                    chrome.tabs.sendMessage(tab.id, function() {
                        console.log('all injected');
                    });
                });
            });
        });
        //getlink();
    });
});


function checkUserAuth() {
    console.log(localStorage.getItem("apiKey"));
    if (localStorage.getItem("apiKey") != null) {
        document.getElementById('openBackgroundWindow').style.visibility = 'hidden';
    }
}

var port = chrome.extension.connect({
    name: "Sample Communication"
});
port.postMessage("Hi BackGround");
port.onMessage.addListener(function(msg) {
    console.log("message recieved" + msg);
});

我的background.js

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");

  });

从网址发送消息的脚本:

document.getElementById("theButton").addEventListener("click", function() {
    console.log("message being sent");
    window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" }, "*");
}, false);

我在哪里错了,我没有收到任何消息?

1 个答案:

答案 0 :(得分:3)

对您的脚本进行一些更改后,我将其运行:)

此问题涵盖来自extension page -- > backgroundcontent page -- > backgroundextension page --> content page

的讯息传递

目标网页的输出(就我而言,http://www.google.co.in/http://localhost:3000/signin

enter image description here

popup.js的输出

enter image description here

来自background.js的输出

enter image description here

我在var port = chrome.extension.connect({name: "Sample Communication"});的popup.js中添加了background.js代码的连接侦听器,解决了Receiving end do not exist的问题

<强> background.js

chrome.extension.onConnect.addListener(function(port) {
    port.onMessage.addListener(function(content) {
        console.log("Connected ..." + content);
    });
});
chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
        "from a content script:" + sender.tab.url :
        "from the extension");
});

通过查找tabs.onUpdated监听器

,在创建新标签时立即消除脚本注入,并在标签状态完成后注入脚本

<强> popup.js

flag = false;
function customFunction() {
    chrome.tabs.create({
        'url': 'http://www.google.co.in/'
    }, function(tab) {
        flag = true;
        // Tab opened.
    });
}

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (flag) {
        if (changeInfo.status === 'complete') {
            console.log("Inject is called");
            injectScript(tab);
        }
    }
});

function injectScript(tab) {
    chrome.tabs.executeScript(tab.id, {
        file: "jquery.js",
        "runAt": "document_start"
    }, function() {
        console.log('all injected');
        chrome.tabs.executeScript(tab.id, {
            file: "content.js",
            "runAt": "document_start"
        }, function() {
            console.log('all injected');
            chrome.tabs.sendMessage(tab.id, function() {
                console.log('all injected');
            });
        });
    });
}

window.onload = function() {
    document.getElementById("linkify").onclick = customFunction;
};

var port = chrome.extension.connect({
    name: "Sample Communication"
});
port.postMessage("Hi BackGround");
port.onMessage.addListener(function(msg) {
    console.log("message recieved" + msg);
});

从网页上删除window.postMessage()并注入一个自定义脚本,点击按钮向popup.js发送消息(此处我选择了Google徽标)

<强> content.js

function bindFunction() {
    console.log("message being sent");
    chrome.extension.sendMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" });
}

window.onload = function() {
    document.getElementById("hplogo").onclick = bindFunction;
};

示例页面linkify按钮类似于登录按钮

<强> popup.html

<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<button id="linkify">Linkify</button>
</body>
</html>

确保所有代码在manifest.json中拥有完整manifest.json文件中注入的脚本文件,标签等的权限

<强> 的manifest.json

{
  "name": "Complex Calls",
  "description": "Complex Calls Demo",
  "manifest_version": 2,
  "background": {
    "scripts": ["background.js"]
  },
  "browser_action": {
    "default_popup": "popup.html",
    "default_icon": "screen.png"
  },
  "permissions": [
    "tabs", "<all_urls>"
  ],
  "version": "1"
}