在Chrome内容脚本和弹出脚本之间共享redux存储

Sharing a redux store between Chrome content script and popup script

本文关键字:脚本 之间 共享 redux 存储 Chrome      更新时间:2023-09-26

如何在Chrome扩展的内容脚本和弹出脚本之间同步Redux存储?它们在两个独立的环境中运行。我知道Chrome中有消息传递功能可以进行通信。

我想知道该如何将其与Redux商店集成。或者我应该只使用Chrome的存储来帮助同步Redux商店吗?

刚刚遇到这个问题,想让未来的访问者知道有一个更新的包(因为这个问题被问到了),它是一个使用React和Redux构建Chrome扩展的基本实用程序库。。。在最高级别,它充当"代理存储",在UI组件和后台页面之间传递操作和状态更改。在OP的场景中可能有用。https://github.com/tshaddix/react-chrome-redux/wiki/Introduction

如果您想在不同的作用域之间重用任何东西,您需要在一个作用域中声明它,并使用与其他作用域之间的消息传递。

manifest.json

{
    "name": "Foo",
    "description": "Bar",
    "version": "2.0",
    "content_scripts": [{
        "js": ["content.js"],
        "matches": "<all_urls>"
    }],
    "background": {
        "scripts": [
            "background.js"
        ],
    },
    "browser_action": {
        "default_popup": "popup.html"
    },
    "manifest_version": 2
}

popup.html

<!DOCTYPE html>
<html>
<head>
<script type="application/x-javascript" src="./popup.js"></script>
</head>
</html>    

background.js

var store = createStore(...);
// <...>
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
     if (request.action === 'dispatch') {
         store.dispatch(request.arg);
         sendResponse('success');
     }
});

popup.js

var BG = chrome.extension.getBackgroundPage();
var store = BG.store;
// <...>

content.js

var msg = { action: 'dispatch', arg: { type: 'INCREMENT' }};
chrome.runtime.sendMessage(msg, function(response) {
    console.log(response) // 'success'
});

有关范围隔离和消息传递,请参阅指导视频。