问题
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