You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript(无jQuery)从多个HTML文件的script标签中获取变量?

如何用JavaScript获取多个HTML文件中的target_date变量

我在一个目录下有多个HTML文件:

file_1.html
file_2.html
file_3.html

每个文件中都包含这段script代码:

<script type="text/javascript">
    var target_date = new Date('December 25, 2022 00:00:00').getTime() + (86400000); 
</script>

我写了一段循环文件的代码,但不知道怎么获取每个文件里的target_date变量:

async function loopFiles() {
    const filesNumber = 3;
    for (step = 0; step < filesNumber; step++){
        console.log(step);
        // 这里该怎么获取每个文件里的target_date变量?
    }
}

解决方案分两种场景处理:

场景1:浏览器环境(加载HTML文件获取)

如果是在浏览器中操作,可通过创建iframe加载目标HTML,再访问iframe的全局上下文拿到变量:

async function loopFiles() {
    const filesNumber = 3;
    // 加let声明step,避免全局变量污染
    for (let step = 0; step < filesNumber; step++){
        const fileName = `file_${step + 1}.html`;
        // 创建隐藏的iframe
        const iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        document.body.appendChild(iframe);

        // 等待iframe加载完成
        await new Promise(resolve => {
            iframe.onload = resolve;
            iframe.src = fileName;
        });

        // 从iframe的全局window中获取target_date
        const targetDate = iframe.contentWindow.target_date;
        console.log(`file_${step + 1}的target_date值:`, targetDate);

        // 用完移除iframe,避免内存占用
        document.body.removeChild(iframe);
    }
}

⚠️ 注意:这种方式受同源策略限制,只有当HTML文件和当前页面同域名/同协议/同端口时才能生效。


场景2:Node.js环境(读取本地文件解析)

如果是在Node.js里处理本地HTML文件,可读取文件内容后用正则匹配提取变量值:

方式1:直接执行匹配到的代码片段(需确保文件可信)

const fs = require('fs').promises;
const path = require('path');

async function loopFiles() {
    const filesNumber = 3;
    for (let step = 0; step < filesNumber; step++){
        const fileName = `file_${step + 1}.html`;
        const filePath = path.resolve(__dirname, fileName);
        
        // 读取文件内容
        const content = await fs.readFile(filePath, 'utf8');
        
        // 正则匹配target_date的赋值语句
        const regex = /var target_date = (.*?);/;
        const match = content.match(regex);
        
        if (match) {
            // 执行匹配到的代码获取值
            const targetDate = eval(match[1]);
            console.log(`file_${step + 1}的target_date值:`, targetDate);
        } else {
            console.log(`未在file_${step + 1}.html中找到target_date变量`);
        }
    }
}

方式2:提取日期字符串手动计算(更安全,无需eval)

const fs = require('fs').promises;
const path = require('path');

async function loopFiles() {
    const filesNumber = 3;
    for (let step = 0; step < filesNumber; step++){
        const fileName = `file_${step + 1}.html`;
        const filePath = path.resolve(__dirname, fileName);
        
        const content = await fs.readFile(filePath, 'utf8');
        // 正则提取日期字符串部分
        const regex = /new Date\('(.*?)'\).getTime\(\) \+ \(86400000\)/;
        const match = content.match(regex);
        
        if (match) {
            // 手动计算target_date的值
            const targetDate = new Date(match[1]).getTime() + 86400000;
            console.log(`file_${step + 1}的target_date值:`, targetDate);
        } else {
            console.log(`未在file_${step + 1}.html中找到target_date变量`);
        }
    }
}

⚠️ 注意:如果文件内容不可信,不要用eval,优先选择第二种方式。


内容的提问来源于stack exchange,提问作者Pro Girl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 21:25:37