【发布时间】: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”?
【问题讨论】:
-
您需要将您的方法绑定到
thismyFoo=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