我正在尝试使谷歌Chrome扩展。
一开始,我想创建一个javascript类,它代表活动的浏览器选项卡,让我使用那个HTML源。应该这样使用:
var currentTab = new CurrentTab();
currentTab.requestHtml(function(html){
// `html` contents active tab HTML
});
我谷歌了一下,我发现活动选项卡的HTML不能直接得到扩展的弹出。但我可以通过我自己的javascript标签,通过chrome.extension.sendRequest()
响应他的HTML到我的扩展。所以,我的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
在这里是未定义的。
请问,我怎么能解决这个问题,为什么会发生?谢谢。
使用Function.prototype.bind
:
var CurrentTab = function(){
...
chrome.extension.onRequest.addListener(this._processListener.bind(this));
};