我对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}
但是当我将“response”的值传递给“this.myObjectExtension”时,控制台显示如下:
TypeError: Cannot set property 'myObjectExtension' of undefined
我理解在方法内部var "this.myObjectExtension"未定义,那么我该如何检索“响应”并将其分配给我的变量“this.myObjectExtension”?
this
上。例如:myFoo = function(abc) { console.log(abc); }.bind(this);
现在你可以在方法内部访问this
了。例如:chrome.runtime.sendMessage(extensionID, 'getObject', myFoo);
- Pranoy SarkarmyFoo=function(response){ console.log(response); this.myObjectExtension=response; }
和public getObjectChrome(){ this.myFoo.bind(this); chrome.runtime.sendMessage(extensionID, 'getObject', this.myFoo); }
这两段代码都运行良好,但是我无法将response的值赋给myObjectExtension。 - AfroChase