Java-script,谷歌chrome扩展:未定义的类变量,在方法中引用的回调

Java-script, Google chrome extension: Undefined class variable, in method referenced by callback

本文关键字:方法 引用 回调 类变量 未定义 谷歌 chrome 扩展 Java-script      更新时间:2023-09-26

我正在尝试使谷歌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));
};