(私はすでにこれを読んでいますが、うまくいきませんでした.
Chrome 開発者ツール用のより優れたコンソール タブを構築することを目的として、Chrome 拡張機能 ( BigConsole ) を作成しています。これは、ページ上の DOM やその他の変数にアクセスして、ページのコンテキストでユーザー入力コードを実行したいということです。これを行うために、通信は次のように構成されています。
devtools
panel
ユーザーがコードを書く場所を作成します- ユーザが からコードを実行する場合、 はコードを含むメッセージをスクリプトに
panel
送信します。panel
background
background
スクリプトはメッセージ/コードを受け取り、ページに挿入されるスクリプトpanel
に渡しますcontent
- スクリプトは
content
スクリプトからメッセージ/コードを受け取り、background
要素script
をページに挿入してコードを実行します。 script
ページでの結果は、content
window.postMessage を使用してスクリプトに戻されます。content
スクリプトはページからのメッセージ/結果をリッスンし、それをスクリプトbackground
に渡します- スクリプトは、
background
スクリプトからメッセージ/結果を受け取り、content
それをpanel
- はスクリプト
panel
からメッセージ/結果を受け取り、background
それを結果のログに挿入します。
うわー。
現在、ユーザーがコードを実行しようとしても、何も起こりません。コードにたくさんのconsole.log()
s を入れましたが、コンソールには何も表示されません。私の主な質問は、何も起こらないメッセージ パッシングでここで何が間違っているのかということです。あるいは、私がこの方法を複雑にしすぎており、物事を行うためのより良い方法があると言われたい. 以下の簡略化されたコード...
panel.js:
window.onload = function() {
var port = chrome.runtime.connect({name: "Eval in context"});
// Add the eval'd response to the console when the background page sends it back
port.onMessage.addListener(function (msg) {
addToConsole(msg, false);
});
document.getElementById('run').addEventListener('click', function() {
var s = document.getElementById('console').value;
try {
// Ask the background page to ask the content script to inject a script
// into the DOM that can finally eval `s` in the right context.
port.postMessage(s);
// Outputting `s` to the log in the panel works here,
// but console.log() does nothing, and I can't observe any
// results of port.postMessage
}
catch(e) {}
});
};
background.js:
chrome.runtime.onConnect.addListener(function (port) {
// Listen for message from the panel and pass it on to the content
port.onMessage.addListener(function (message) {
// Request a tab for sending needed information
chrome.tabs.query({'active': true,'currentWindow': true}, function (tabs) {
// Send message to content script
if (tab) {
chrome.tabs.sendMessage(tabs[0].id, message);
}
});
});
// Post back to Devtools from content
chrome.runtime.onMessage.addListener(function (message, sender) {
port.postMessage(message);
});
});
content.js:
// Listen for the content to eval from the panel via the background page
chrome.runtime.onMessage.addListener(function (message, sender) {
executeScriptInPageContext(message);
});
function executeScriptInPageContext(m) { alert(m); }