Google Chrome 拡張機能を作ろうとしています。
最初に、アクティブなブラウザー タブを表す JavaScript クラスを作成し、その HTML ソースを操作できるようにします。次のように使用する必要があります。
var currentTab = new CurrentTab();
currentTab.requestHtml(function(html){
// `html` contents active tab HTML
});
ググったところ、アクティブなタブの HTML を拡張機能のポップアップに直接取得できないことがわかりました。しかし、独自の JavaScript をタブに渡すことができますchrome.extension.sendRequest()
。したがって、私のCurrentTab
クラスは次のようになります。
var CurrentTab = function(){
this.listeners = {
'requestHtml': {}
};
chrome.extension.onRequest.addListener(this._processListener);
};
CurrentTab.prototype = {
requestHtml: function(callback){
var actionKey = Math.ceil(Math.random() * 10000); // get random identifier for this callback
this.listeners['requestHtml'][actionKey] = callback;
chrome.tabs.executeScript(null, {
code: 'console.log("SendContent.js");'
+ 'chrome.extension.sendRequest({'
+ ' action: "' + actionKey + '",'
+ ' host: document.location.hostname,'
+ ' content: document.getElementsByTagName("html")[0].outerHTML'
+ '}, function(response){});'
});
},
_processListener: function(request, sender, sendResponse){
/*25.*/console.log(this.listeners); // `this.listeners` is 'undefined' ???
if (this.listeners['requestHtml'][request.action]) {
this.listeners['requestHtml'][request.action](request.content);
delete this.listeners['requestHtml'][request.action];
}
}
};
問題はこのクラスの 25 行目です。メソッド_processListener
はクラスの一部ですが、このメソッドがコールバック経由で呼び出される場合CurrentTab
、変数はここでは未定義です。this.listeners
どうすればこれを修正できますか、なぜそれが起こっているのですか? ありがとう。