【问题标题】:IE11 iframe cached content has wrong encodingIE11 iframe 缓存内容编码错误
【发布时间】:2019-08-27 16:09:33
【问题描述】:

我有一个动态嵌入 iframe 的网页,它加载包含本地化字符串的 JS 文件:外部页面的内容类型为“Shift-JIS”,但内部框架(和本地化字符串)为“ UTF-8”。结构是这样的:

<html>
  <head>
    <meta charset="shift-JIS" >
  </head>
  <body>
    <iframe id="my-frame" src="my-frame.html">
       <html>
          <head>
            <meta charset="utf-8" />
            <script src="my-i18n.js" charset="utf-8" />
          </head>
       </html>
    </iframe>
  </body>
</html>

在初始渲染时,内容正确显示。但是在重新加载时,在 Internet Explorer 11 中,如果从 IE 的缓存返回 my-i18n.js,则 utf-8 编码的内容将被解释为 shift-JIS 编码的内容,并且在视觉上会被破坏。

仅当 IE 从缓存中返回本地化字符串时。如果我打开 devtools 并单击“始终从服务器刷新”以禁用缓存,它每次都呈现良好。

有没有办法解决这个问题,或者解决它?

【问题讨论】:

    标签: internet-explorer character-encoding internet-explorer-11 browser-cache shift-jis


    【解决方案1】:

    在我的测试中,我发现如果我每次给 iframe 一个随机的 id,iframe 会在 IE 中被强制刷新。脚本是这样的:

     var randomNum = Math.floor(Math.random() * 100000);
     somecontainer.innerHTML = '<iframe src="xxx.html" id="' + randomNum + '"></iframe>';
    

    如果你想在每次刷新时重新加载 js 文件,你可以像这样在脚本的 src 链接中添加一个随机参数:

    <script>document.write('<script src="my-i18n.js?dev=' + Math.floor(Math.random() * 100) + '"><\/script>');</script>
    

    【讨论】:

    • 问题不是 iframe 本身刷新,而是 iframe 从缓存中加载的依赖关系。即使“#my-frame”重新加载,如果“my-i18n.js”从缓存中返回,内容格式错误。
    • 我已经更新了我的答案,您可以尝试我的答案中的解决方案。如果问题仍然存在,最好提供一个简单的示例来重现该问题。以便我们对问题有更好的理解。感谢您的理解。
    【解决方案2】:

    不幸的是,我没有找到任何方法来修复此行为 - 它似乎只是 IE 的一个未修复的错误。

    相反,我们将本地化字符串转换为不包含 unicode 字符,用 unicode 转义序列替换它们,通过:

    const leftPad = str => ('0000' + str).slice(-4);
    
    const escapeUnicode = str => (
        str.split('')
            .map(char => {
                const cp = char.codePointAt(0);
                if (cp < 128) return char; //Preserve ASCII characters
                return `\\u${leftPad(cp.toString(16).toUpperCase())}`;
            })
            .join('')
    );
    

    这避免了确定文件采用什么编码的整个问题,因为整个文件都是 ACSII。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多