从background.js发送消息到popup



我想在我的chrome扩展中实现FCM。目前,经过大量的研究,我发现实现fcm的快速和最好的方法是使用旧的APIchrome.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驱动的弹出窗口和扩展的背景文件之间传递消息?

是使用firebase客户端库来获取推送消息更好,还是gcm适合此范围?

您可以使用chrome.tabs.querychrome.tabs.sendMessageapi从后台向弹出窗口发送消息。

chrome.tabs.query({}, function (tabs) {
tabs.forEach((tab) => {
chrome.tabs.sendMessage( 
tab.id,
youtPayload, 
function (response) {
// do something here if you want
}
);
});
});

就是这样!

我花了很多时间去寻找解决同一个问题的方法,但仍然一无所获。

我目前的理解是,我们正在努力做和使用的方法的目的,他们不被用于。

导致此结果的关键信息:

  • pop .js可以共享。Js文件和object with background.js
  • 文档主要是谈论在网页(content.js)和其他(pop .js或background.js)之间传递数据

最新更新