在Chrome内容脚本和弹出脚本之间共享redux商店

时间:2015-12-26 20:50:55

标签: javascript google-chrome google-chrome-extension redux

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

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

2 个答案:

答案 0 :(得分:3)

刚刚遇到这个问题,并希望让未来的访问者知道有更新的软件包(因为这个问题被问到)这是一个基本的实用程序库,用于构建具有React和Redux的Chrome Extensions ......在最高级别,它充当代理商店'在UI组件和后台页面之间传递操作和状态更改。在OP的情况下可能有用。 https://github.com/tshaddix/react-chrome-redux/wiki/Introduction

答案 1 :(得分:2)

如果要在不同范围之间重复使用任何内容,则需要将其声明为一个,并使用与其他人的消息传递。

的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'
});

请参阅scope isolationmessaging的教学视频。

相关问题