1

I am trying to send a message from a button click even on my website which is opened in a tab by chrome extension.

But, I'm not able to get any message from the webpage and I get a port error.

My 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);
});

My background.js

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

  });

Script that sends message from the web url:

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

Where am I going wrong here that I am not receiving any message?

4

1 に答える 1

3

スクリプトにいくつかの変更を加えた後、実行しました:)

extension page -- > backgroundこの質問は、からのメッセージの受け渡しを対象としていますcontent page -- > backgroundextension 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

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);
});

Web ページから削除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

マニフェスト.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 に答える