首页 > 解决方案 > 值出现在 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 时我总是不确定。我觉得这应该很简单,但我不知道问题出在哪里。

标签: javascriptgoogle-chrome-extensionyoutube

解决方案


推荐阅读