Javascript Chrome扩展:获取从background.js到popup.js的变量
我正在用babel软件包制作我的第一个chrome扩展,它可以在每个网页上记录你的时间。我在后台启动开始时间,但当他们单击弹出窗口时,需要访问popup.js中的开始时间。我需要弄清楚如何做到这一点,因为这一切的异步性似乎都在阻碍我。以下是相关文件: json(我确实使用了持久化背景,因为这似乎是实现计时器的最佳方式,尽管文档不鼓励使用它。) popup.js:Javascript Chrome扩展:获取从background.js到popup.js的变量,javascript,reactjs,google-chrome,google-chrome-extension,Javascript,Reactjs,Google Chrome,Google Chrome Extension,我正在用babel软件包制作我的第一个chrome扩展,它可以在每个网页上记录你的时间。我在后台启动开始时间,但当他们单击弹出窗口时,需要访问popup.js中的开始时间。我需要弄清楚如何做到这一点,因为这一切的异步性似乎都在阻碍我。以下是相关文件: json(我确实使用了持久化背景,因为这似乎是实现计时器的最佳方式,尽管文档不鼓励使用它。) popup.js: import "../css/popup.css"; import Timer from "./popup/timer_compone
import "../css/popup.css";
import Timer from "./popup/timer_component.js";
import React from "react";
import { render } from "react-dom";
const console = chrome.extension.getBackgroundPage().console;
let startingTime;
chrome.runtime.sendMessage({request: "getStartTime"}, function(response) {
startingTime = response.done;
});
render(
<Timer currentTimer = {startingTime}/>,
window.document.getElementById("app-container")
);
这里的问题是消息是异步的,因此startingTime
没有及时更新以将其传递给渲染函数。我想知道我该怎么做?在尝试传递消息之前,我尝试直接使用startingTime=chrome.extension.getBackgroundPage().startTime访问变量
,但这似乎也可能是异步的,因为startingTime
在到达渲染函数时仍然没有定义
如果您能提供任何帮助,甚至是正确方向上的一点帮助,我都将不胜感激,因为我对这个路障已经没有什么想法了。您可以将popup.js更改为不调用ReactDOM.render,直到它从后台获得所需的数据
chrome.runtime.sendMessage({request: "getStartTime"}, function(response) {
const startingTime = response.done;
render(
<Timer currentTimer = {startingTime}/>,
window.document.getElementById("app-container")
);
});
chrome.runtime.sendMessage({request:“getStartTime”},函数(响应){
const startingTime=response.done;
渲染(
,
window.document.getElementById(“应用程序容器”)
);
});
当我为我的扩展做这件事时,我注意到一个chrome错误,弹出窗口的尺寸设置不正确。如果发生这种情况,可以在HTML中设置宽度和高度
import '../img/icon-128.png'
import '../img/icon-34.png'
const console = chrome.extension.getBackgroundPage().console;
let startTime = Date.now();
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.request == "getStartTime") {
sendResponse({done: startTime});
}
});
chrome.runtime.sendMessage({request: "getStartTime"}, function(response) {
const startingTime = response.done;
render(
<Timer currentTimer = {startingTime}/>,
window.document.getElementById("app-container")
);
});