3

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"?

AfroChase
  • 178
  • 2
  • 14
  • you need to bind your method to `this` `myFoo=function(abc){ console.log(abc); }` bind your method withthe scope `myFoo.bind(this)` now you can access this inside your method, `chrome.runtime.sendMessage(extensionID, 'getObject', myFoo)` – Pranoy Sarkar Feb 20 '18 at 17:28
  • I don't know if I did it correctly. Look: `myFoo=function(response){ console.log(response); this.myObjectExtension=response; }` and `public getObjectChrome(){ this.myFoo.bind(this); chrome.runtime.sendMessage(extensionID, 'getObject', this.myFoo); }` Both codes work well but I cannot assing the value of response to myObjectExtension. – AfroChase Feb 20 '18 at 20:15
  • I found this https://stackoverflow.com/questions/21560137/scope-in-chrome-message-passing, you are correct @Pranoy Sarkar, post your answer. – AfroChase Feb 20 '18 at 20:54

1 Answers1

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.

AfroChase
  • 178
  • 2
  • 14