javascript - 值出现在 console.log 中,但在通过 innerHTML 分配时未定义
问题描述
当单击我的扩展程序上的按钮时,我正在尝试获取 YouTube 视频的时间戳。现在,我的代码设置如下:
contentScript.js
var time;
function get_timestamp() {
time = document.getElementsByClassName('video-stream')[0].currentTime
console.log(time);
return time;
};
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.message === "pause_video") {
pause_video();
}
if (request.message === "get_time") {
sendResponse({timestamp: get_timestamp()})
}
}
);
暂停功能也在同一个文件中定义并按预期工作。
popup.js
function get_time() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {message: "get_time"}, function(response) {
console.log(response.timestamp.toString());
return response.timestamp.toString();
});
})
};
popup2.js
document.getElementById("time").innerHTML = get_time();
popup2.js 中的行位于按下按钮时调用的函数中。作为测试的一部分,该脚本被拆分为 2 个文件,但如有必要,可以将它们组合起来。程序的其余部分按预期工作,具有暂停视频和从 url 获取 videoID 的功能正常工作。所有的 console.log 命令都显示了视频的当前时间戳,但是当我使用 innerHTML 时我总是不确定。我觉得这应该很简单,但我不知道问题出在哪里。
解决方案
推荐阅读
- python - Pytest 无法通过标记 skipif 跳过类中的测试用例
- swift - Xcode 错误:中止陷阱 6
- swift - 如何快速更改图像方向
- ubuntu - 将 SSH 文件复制到另一台机器
- android - TextView,它是动态生成的,顶部有额外的填充?
- python - python count 变量在我的主函数中调用回主函数时没有更新
- powerbi - 每个国家的摩天大楼数量
- python - Python - 可以从特定字符串输入中获取所有日期的日期解析器
- angular - 限制用户同时访问 WebAPI 而不是 SPA 网站
- php - MYSQL JOIN 查询需要很长时间才能执行