1

我正在尝试通过单击按钮发送消息,即使在我的网站上也是如此,该网站是通过 chrome 扩展程序在选项卡中打开的。

但是,我无法从网页中获取任何消息,并且出现端口错误。

我的 content.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);
});

我的背景.js

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

  });

从 Web url 发送消息的脚本:

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

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

4

1 回答 1

3

在对您的脚本进行一些更改后,我让它运行了:)

extension page -- > background此问题涵盖从, content page -- > background,传递的消息extension page --> content page

目标页面的输出(在我的情况下,它是http://www.google.co.in/给你的http://localhost:3000/signin

在此处输入图像描述

popup.js 的输出

在此处输入图像描述

来自 background.js 的输出

在此处输入图像描述

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

背景.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 发送消息(这里我选择了谷歌徽标)

内容.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

清单.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"
}
于 2012-11-30T03:19:32.273 回答