我想在我的chrome扩展中实现FCM。在经过大量研究后,我发现实现fcm的最快和最好的方法是使用旧的API chrome.gcm
。目前,这个解决方案似乎工作得很好,当扩展加载时,我能够获得fcm令牌。
现在,我想做的是将令牌传递给由vue.js提供支持的弹出窗口,我尝试使用此代码,但没有成功。
background.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)
})
弹出.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适合这个范围?
2条答案
按热度按时间cgh8pdjw1#
您可以使用
chrome.tabs.query
和chrome.tabs.sendMessage
API将消息从后台发送到Popup。就是这样!
smtd7mpg2#
我花了很多时间去寻找解决同样问题的方法,但仍然没有找到。
我目前的理解是,我们正在努力做到这一点,并使用方法的目的,他们不是要使用。
导致此结果的关键信息: