如何在Angular 4中从chrome.runtime.sendMessage获取回调?

3

我对Angular 4和Chrome扩展程序的使用非常新,但我有以下代码,可以让我的Angular应用程序与Chrome扩展程序进行通信。

Angular 4中的代码。

public myObjectExtension : any;

public getObjectChrome(){
    chrome.runtime.sendMessage(extensionID, 'getObject', function(response) {
        console.log(response);
        this.myObjectExtension = reponse;
  });

我有一个Chrome扩展程序,其中包含以下内容:

chrome.runtime.onMessageExternal.addListener(
   function(request, sender, sendResponse) {
     if(request == "getObject"){
          sendResponse({
              name: "Afro",
              lastname: "Chase"
          });
     }

当我运行应用程序时,控制台日志会正确显示数据,就像这样。
{name: "Afro", lastname: "Chase}

但是当我将“response”的值传递给“this.myObjectExtension”时,控制台显示如下:
TypeError: Cannot set property 'myObjectExtension' of undefined

我理解在方法内部var "this.myObjectExtension"未定义,那么我该如何检索“响应”并将其分配给我的变量“this.myObjectExtension”?


你需要将你的方法绑定到 this 上。例如:myFoo = function(abc) { console.log(abc); }.bind(this);现在你可以在方法内部访问 this 了。例如:chrome.runtime.sendMessage(extensionID, 'getObject', myFoo); - Pranoy Sarkar
我不知道我是否做对了。看一下:myFoo=function(response){ console.log(response); this.myObjectExtension=response; }public getObjectChrome(){ this.myFoo.bind(this); chrome.runtime.sendMessage(extensionID, 'getObject', this.myFoo); } 这两段代码都运行良好,但是我无法将response的值赋给myObjectExtension。 - AfroChase
我找到了这个链接:https://stackoverflow.com/questions/21560137/scope-in-chrome-message-passing,你是对的@Pranoy Sarkar,请发表你的答案。 - AfroChase
1个回答

1

好的,我认为这个问题是重复的。查看Chrome消息传递中的作用域,但我不知道如何关闭一个像“完全重复”的问题。

我可以回答这个问题,因为Pranoy Sarkar帮助了我。所以答案是,在方法的内部

chrome.runtime.sendMessage(string extensionId, any message, object options, function responseCallback)

作用域发生变化,因此如果要更改全局变量"myObjectExtension",我们需要将作用域传递到回调函数中。我们可以通过JavaScript的bind方法来实现,像这样:
public getObjectChrome(){
  let myFoo=function(response){
    console.log(response);
    this.myObjectExtension = reponse;
  }
  chrome.runtime.sendMessage(extensionID, 'getObject' myFoo.bind(this));
}

而且这段代码运行得非常好。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接