how to get the Callback from chrome.runtime.sendMessage in Angular 4?

别来无恙 提交于 2021-02-10 06:26:31

问题


I am really new working with Angular 4 and Chrome Extensions, but I have this code to comunicate my app in Angular with the Chrome extension.

Code in Angular 4.

public myObjectExtension : any;

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

}

and I have this in my Chrome Extension.

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

When I run the application the console log show me correctly the data, like this.

{name: "Afro", lastname: "Chase}

but when I pass the value of "reponse" to "this.myObjectExtension", the console shows me this

TypeError: Cannot set property 'myObjectExtension' of undefined

I undestand that var "this.myObjectExtension" is not defined inside of the method, but how can I do to retrive the "response" and assign it to my var "this.myObjectExtension"?


回答1:


Ok, I think this question is duplicate. Check this Scope in chrome message passing but I don't know how to close a question like "exact duplicate".

I could answer the question because Pranoy Sarkar helps me. So the answer is this, inside the of the method

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

the scope changes, so to alter a global variable like "myObjectExtension" we have to pass the scope into the callback. We can do it through the javascript bind method, like this:

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

And the code works like a charm.



来源:https://stackoverflow.com/questions/48876768/how-to-get-the-callback-from-chrome-runtime-sendmessage-in-angular-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!