繁体   English   中英

将消息从 background.js 发送到弹出窗口

[英]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.querychrome.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
        }
      );
    });
  });

而已!

我花了很多时间来寻找相同问题的解决方案,但仍然没有找到任何解决方案。

我目前的理解是,我们正在尝试做和使用方法的目的,而不是为了使用它们。

导致这一点的关键信息:

  • popup.js 可以共享相同的。 带有 background.js 的 Js 文件和对象
  • 文档主要是关于在 web 页面 (content.js) 和其他页面(popup.js 或 background.js)之间传递数据

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM