[英]Continually send message from background.js to popup.js in setInterval but only when popup is opened?
[英]Send message from background.js to popup
我想在我的 chrome 擴展中實現 FCM。 在經過大量研究后,我發現實現 fcm 的快速和最佳方法是使用舊的 API chrome.gcm
。 目前這個解決方案似乎工作正常,當加載擴展時我能夠獲得一個 fcm 令牌。
現在我想做的是將令牌傳遞給由 vue.js 提供支持的彈出窗口我正在嘗試使用此代碼但沒有成功。
背景.js
const openPopup = () => {
chrome.windows.create({
type: 'popup',
height: 520,
width: 440,
url: chrome.runtime.getURL('popup.html')
})
}
const registeredToken = (registrationId) => {
console.log('FCM Token')
console.log(registrationId)
openPopup()
chrome.runtime.sendMessage({fcmToken: registrationId})
if( chrome.runtime.lastError ) {
console.log('error')
}
}
const notificationId = (id) => {
if(chrome.runtime.lastError) {
console.log(chrome.runtime.lastError)
}
console.log(id)
}
chrome.runtime.onInstalled.addListener( () => {
console.log('FCM extension installed')
})
chrome.action.onClicked.addListener( (tab) => {
console.log(tab)
openPopup()
})
chrome.gcm.register(['my_sender_id'], registeredToken)
chrome.gcm.onMessage.addListener( (message) => {
console.log(message, message.data["gcm.notification.title"])
chrome.notifications.create('', {
type: 'basic',
iconUrl: 'letter.png',
title: message.data["gcm.notification.title"],
message: message.data["gcm.notification.body"],
buttons: [
{ title: 'Dismiss' },
{ title: 'Reply' }
]
}, notificationId)
})
chrome.notifications.onButtonClicked.addListener( (notificationId, buttonIndex) => {
console.log('button clicked')
console.log(notificationId, buttonIndex)
})
popup.vue 文件
<template>
<div class="main_app">
<h1>Hello {{msg}}</h1>
</div>
</template>
<script>
export default {
name: 'popupView',
data () {
return {
msg: ''
}
},
mounted() {
chrome.runtime.onMessage( (message, sender, sendResponse) => {
console.log(message, sender, sendResponse)
this.msg = message
})
},
methods: {
}
}
</script>
我注意到的是chrome.runtime.sendMessage({fcmToken: registrationId})
將不起作用,並且在彈出窗口方面我無法從后台發送或獲取消息
我如何在 vue.js 驅動的彈出窗口和擴展程序的 background.js 文件之間傳遞消息?
是更好地使用 firebase 客戶端庫來獲取推送消息還是 gcm 適合這個 scope?
您可以使用chrome.tabs.query
和chrome.tabs.sendMessage
API將消息從后台發送到 Popup。
chrome.tabs.query({}, function (tabs) {
tabs.forEach((tab) => {
chrome.tabs.sendMessage(
tab.id,
youtPayload,
function (response) {
// do something here if you want
}
);
});
});
而已!
我花了很多時間來尋找相同問題的解決方案,但仍然沒有找到任何解決方案。
我目前的理解是,我們正在嘗試做和使用方法的目的,而不是為了使用它們。
導致這一點的關鍵信息:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.