如何从Angular 4中的chrome.runtime.sendMessage获取回调? [英] how to get the Callback from chrome.runtime.sendMessage in Angular 4?
问题描述
我真的是使用Angular 4和Chrome扩展程序的新手,但是我有这段代码可以将我在Angular中的应用程序与Chrome扩展程序进行通讯.
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.
Angular 4中的代码.
Code in Angular 4.
public myObjectExtension : any;
public getObjectChrome(){
chrome.runtime.sendMessage(extensionID, 'getObject', function(response) {
console.log(response);
this.myObjectExtension = reponse;
});
}
并且我在Chrome扩展程序中拥有它.
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}
但是当我将响应"的值传递给"this.myObjectExtension"时,控制台会向我显示此内容
but when I pass the value of "reponse" to "this.myObjectExtension", the console shows me this
TypeError: Cannot set property 'myObjectExtension' of undefined
我无法理解方法内部没有定义var"this.myObjectExtension",但是我该如何检索响应"并将其分配给我的var"this.myObjectExtension"?
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"?
推荐答案
好的,我认为这个问题是重复的.选中此 Chrome邮件传递中的作用域,但我不知道如何解决问题例如完全重复".
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".
我可以回答这个问题,因为Pranoy Sarkar帮助了我.答案是这样的,在方法的内部
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)
范围发生了变化,因此要更改"myObjectExtension"之类的全局变量,我们必须将范围传递给回调.我们可以通过javascript bind方法来做到这一点,就像这样:
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.
这篇关于如何从Angular 4中的chrome.runtime.sendMessage获取回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!