1 回答

TA貢獻1821條經(jīng)驗 獲得超5個贊
可以為此使用chrome.runtime.onConnect(感謝@wOxxOm):
在 React 組件的構造函數(shù)中打開一個連接:
constructor(props){
super(props)
this.state = {
dance: false,
}
...
var port = this.xbrowser.runtime.connect();
...
}
componentDidMount在反應組件中添加事件。
async componentDidMount(){
...
// an object from the background is retrieved
let background_object = this.props.getBackgroundObject();
...
// add event (eventemitter3 is used for the event management)
background_object.event.on('onMusic', this.dance);
...
}
async dance() {
this.setState({
'music': true,
})
}
在后臺的某個地方(例如background.js)偵聽與瀏覽器的連接,并在連接丟失時刪除該事件:
chrome.runtime.onConnect.addListener(function (externalPort) {
externalPort.onDisconnect.addListener(function () {
let background_object = this.props.getBackgroundObject();
background_object.event.removeListener('onSend');
})
})
在我看來,這不是很優(yōu)雅,但它確實有效。
添加回答
舉報