【问题标题】:how to get the Callback from chrome.runtime.sendMessage in Angular 4?如何在 Angular 4 中从 chrome.runtime.sendMessage 获取回调?
【发布时间】:2018-07-30 07:32:05
【问题描述】:

我真的是使用 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}

但是当我将“reponse”的值传递给“this.myObjectExtension”时,控制台会显示这个

TypeError: Cannot set property 'myObjectExtension' of undefined

我不明白 var “this.myObjectExtension” 没有在方法内部定义,但是我该如何检索“响应”并将其分配给我的 var “this.myObjectExtension”?

【问题讨论】:

  • 您需要将您的方法绑定到this myFoo=function(abc){ console.log(abc); } 将您的方法与myFoo.bind(this) 的范围绑定现在您可以在您的方法中访问它,chrome.runtime.sendMessage(extensionID, 'getObject', myFoo)
  • 我不知道我是否做得对。看:myFoo=function(response){ console.log(response); this.myObjectExtension=response; }public getObjectChrome(){ this.myFoo.bind(this); chrome.runtime.sendMessage(extensionID, 'getObject', this.myFoo); } 两个代码都运行良好,但我无法评估 myObjectExtension 的响应值。
  • 我找到了这个stackoverflow.com/questions/21560137/…,你是对的@Pranoy Sarkar,发布你的答案。

标签: javascript angular google-chrome google-chrome-extension google-chrome-devtools


【解决方案1】:

好的,我认为这个问题是重复的。检查此Scope in chrome message passing,但我不知道如何关闭“完全重复”之类的问题。

我可以回答这个问题,因为 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));
}

代码就像一个魅力。

【讨论】:

    猜你喜欢
    • 2019-04-25
    • 2018-01-05
    • 2018-02-10
    • 1970-01-01
    • 2019-02-14
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-12
    相关资源
    最近更新 更多