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

Chrome最新版本更新后无法加载XSLT文档问题求助

解决Chrome最新版本XHR加载XSLT时responseXML为空的问题

问题分析

Chrome最新版本更新后,使用XMLHttpRequest加载XSLT文件时,responseXML返回空值,但responseText能正常获取内容。这是因为Chrome调整了对XSLT文档的解析逻辑,不再自动将XSLT文件解析为XML文档对象,需要手动通过解析器转换。

解决方案

修改代码,在获取responseText后,使用DOMParser将文本内容解析为application/xml格式的XML文档,同时保留对旧浏览器(如IE)的兼容逻辑:

return new Promise(function (resolve, reject) {
    var req = new XMLHttpRequest();
    req.open("GET", url);
    
    // 保留IE兼容逻辑
    if (typeof XSLTProcessor === 'undefined') {
        try {
            req.responseType = 'msxml-document';
        } catch (e) {
            console.error('设置msxml-document失败:', e);
        }
    }
    
    req.onload = function () {
        if (this.status >= 200 && this.status < 300) {
            // 优先判断是否有可用的responseXML(兼容旧版本Chrome/其他浏览器)
            if (this.responseXML) {
                resolve(this.responseXML);
                return;
            }
            
            // 手动解析responseText为XML文档
            try {
                var parser = new DOMParser();
                var xmlDoc = parser.parseFromString(this.responseText, 'application/xml');
                // 检查解析是否成功(避免解析错误返回空文档)
                if (xmlDoc.documentElement.nodeName !== 'parsererror') {
                    resolve(xmlDoc);
                } else {
                    reject(new Error('解析XSLT文档失败'));
                }
            } catch (e) {
                reject(new Error('解析XSLT文档出错:', e));
            }
        } else {
            reject(new Error('请求XSLT文件失败,状态码:' + this.status));
        }
    };
    
    // 处理网络请求错误
    req.onerror = function () {
        reject(new Error('网络请求失败,无法加载XSLT文件'));
    };
    
    req.send();
});

代码说明

  • 保留原有的IE兼容逻辑,针对不支持XSLTProcessor的浏览器设置responseType为msxml-document
  • 请求成功后,先尝试使用responseXML(兼容旧版本Chrome和其他浏览器),为空则手动解析
  • 使用DOMParser的parseFromString方法将responseText解析为XML文档,指定MIME类型为application/xml
  • 添加了解析错误和网络请求错误的处理,确保Promise能正确抛出异常
  • 增加解析结果校验,避免解析失败时返回错误文档对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 23:55:04