在 Chrome 内容脚本和弹出脚本之间共享一个 redux 存储
Sharing a redux store between Chrome content script and popup script
如何在 Chrome 扩展的内容脚本与其弹出脚本之间同步 Redux 存储?它们在 2 个独立的环境中运行。我知道 Chrome 中有消息传递函数可以进行通信。
我想知道我应该如何将它与 Redux 存储集成。或者我应该只使用 Chrome 的存储来帮助同步 Redux 存储?
如果你想在不同范围之间重用任何东西,你需要在一个范围内声明它并使用消息传递 to/from 其他范围。
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 isolation and messaging 的教学视频。
刚遇到这个问题,想让未来的访问者知道有更新的包(因为这个问题被问到)这是一个基本的实用程序库,用于构建 Chrome 使用 React 和 Redux 扩展...在最高级别,它充当 'proxy store' 在 UI 组件和后台页面之间传递动作和状态更改。在 OP 的场景中可能会有用。
https://github.com/tshaddix/react-chrome-redux/wiki/Introduction
如何在 Chrome 扩展的内容脚本与其弹出脚本之间同步 Redux 存储?它们在 2 个独立的环境中运行。我知道 Chrome 中有消息传递函数可以进行通信。
我想知道我应该如何将它与 Redux 存储集成。或者我应该只使用 Chrome 的存储来帮助同步 Redux 存储?
如果你想在不同范围之间重用任何东西,你需要在一个范围内声明它并使用消息传递 to/from 其他范围。
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 isolation and messaging 的教学视频。
刚遇到这个问题,想让未来的访问者知道有更新的包(因为这个问题被问到)这是一个基本的实用程序库,用于构建 Chrome 使用 React 和 Redux 扩展...在最高级别,它充当 'proxy store' 在 UI 组件和后台页面之间传递动作和状态更改。在 OP 的场景中可能会有用。 https://github.com/tshaddix/react-chrome-redux/wiki/Introduction