问题
I have created a simple extension for Chrome using angular-cli. I want the extension's popup to display the URL of the current tab. However the view does not seem to get updated when setting a property from chrome.tabs.query callback. I have confirmed with a console.log that the callback is getting called and the correct URL is being returned.
What am I doing wrong?
app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
currentLocation = '';
ngOnInit() {
chrome.tabs.query({"active": true, "currentWindow": true}, (tabs) => {
this.currentLocation = tabs[0].url;
console.log(tabs[0].url);
});
}
}
app.component.html
<div>
<h1>
You are at {{ currentLocation }}!
</h1>
</div>
manifest.json
{
"manifest_version": 2,
"name": "Test Extension",
"version": "1.0.0",
"permissions": [
"tabs",
"activeTab"
],
"browser_action": {
"default_title": "Open Popup!",
"default_popup": "index.html"
},
"icons": {
"19": "assets/Icon-19.png",
"38": "assets/Icon-38.png"
},
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
}
回答1:
You could tried like below (using NgZone):
import { Component, NgZone } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
currentLocation = "";
ngOnInit(private _ngZone: NgZone) {
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
this._ngZone.run(() => {
this.currentLocation = tabs[0].url;
});
});
}
}
来源:https://stackoverflow.com/questions/50843416/chrome-tabs-query-callback-in-angular-not-refreshing-view