【问题标题】:Open an html file programatically using javascript in a new browser tab from disk在磁盘的新浏览器选项卡中使用 javascript 以编程方式打开 html 文件
【发布时间】:2014-10-27 17:12:47
【问题描述】:

有没有办法在新标签页中使用 javascript 打开 html 文件?

我希望用户使用<input type="file"> 选择一个html 文件。选择文件后,一些 JavaScript 代码将打开该 html 文件。

【问题讨论】:

  • 在 Google 上搜索“jquery lightbox”,你会发现很多方法可以实现这一点。
  • @Charles,你应该说明你的目标是什么?打开文件以显示html?在 DIV 中加载文件?
  • 不,我希望它显示在新标签中,我知道这听起来很愚蠢,因为用户只需双击 html 文件并打开它。如果不可能,我想知道如何实现在 DIV 中加载文件
  • @Brad,OP 在我发表评论后更改了问题。最初的问题非常模糊。

标签: javascript jquery html file input


【解决方案1】:

您可以为此使用文件 API。您可以执行以下示例。

Here is a live example

仅在最新的 Chrome 和 Firefox 版本中进行了测试。

HTML:

<form action="">
    <p><input type="file" id="userFile"></p>
</form>

<p><a href="" target="_blank" id="newTab" style="display:none">Open File</a></p>
<div id="preview"></div>

**JS:**
(function(window, undefined) {
  var 
    doc = window.document,
    userFile = doc.getElementById('userFile'),
    newTab = doc.getElementById('newTab'),
    preview = doc.getElementById('preview'),
    fileReader = new FileReader();
  
  var fileutil = {
    init: function() {
      userFile.addEventListener('change', fileutil.onchange, false);
    },
    
    onchange: function(e) {
      //console.log(this.files);
      fileutil.create(this.files[0]);
    },
    
    create: function(file) {
      //console.log(file);
      var iframe = doc.createElement('iframe');

      // Start reading file..., and wait to complete.
      fileReader.readAsDataURL(file);      
      
      // When done reading.
      fileReader.onload = function(e) {
        //console.log(e.target.result);
        
        iframe.src = e.target.result;
        iframe.width = '100%';
        iframe.height = 500;
        
        newTab.href = e.target.result;
        newTab.style.display = 'block';
        
        preview.appendChild(iframe);
      };
    }
  };
  
  fileutil.init();
}(this));

更新: -------- 此示例提供对 iframe 文档的访问权限,因此允许您与其通信并更改其内容。

JSFiddle:http://jsfiddle.net/Lxx56hh4/

JS:

(function(window, undefined) {
  var 
    doc = window.document,
    userFile = doc.getElementById('userFile'),
    preview = doc.getElementById('preview'),
  
    // We read the file as Text and then parse it into a DOM Document.
    fileReader = new FileReader(),
    domParser = new DOMParser();
  
  var fileutil = {
    init: function() {
      userFile.addEventListener('change', fileutil.onchange, false);
    },
    
    onchange: function(e) {
      fileutil.create(this.files[0]);
    },
    
    create: function(file) {
      var self = this;

      // An iframe to append the new Document to.
      this.iframe = doc.createElement('iframe');
      this.iframe.width = '100%';
      this.iframe.height = 300;

      // Start reading the file as plain text and wait to complete.
      fileReader.readAsText(file);
      
      // When done reading.
      fileReader.onload = function(e) {
        if (e.target.readyState === 2) { // 2 means DONE
          preview.appendChild(self.iframe);
          fileutil._ready(e.target.result);
        }
      };
    },
      
    _ready: function(ihtml) {
      var iwindow = this.iframe.contentWindow;
      var idocument = iwindow.contentDocument || iwindow.document;
        
      // Create a DOM document out of the text contents.
      var fileDocument = domParser.parseFromString(ihtml, "text/html");
      
      // Make the iframe's body equal the fileDocument's body.
      // We do this so we get only the body's contents and not the whole document.
      idocument.body.innerHTML = fileDocument.body.innerHTML;
      
      
      // We can now communicate with the iframe's body to add or remove elements.
      // With jQuery you can do: 
      // `$(idocument.body).prepend('<h1>Injected H1.</h1>')`
      // 
      // NOTE: Any resources such as stylesheets, images, and scripts referenced in fileDocument may not be available in the iframe.
      // 
      // With VanillaJS you can do:
      idocument.body.insertAdjacentHTML('afterbegin', '<h1>Injected H1.</h1>');
        
      // Using XHR2 you can now send the original file or DOMString to your server.
      // More here: http://www.html5rocks.com/en/tutorials/file/xhr2/#toc-sending
    }
  };
  
  fileutil.init();
}(this));

HTML:

<form action="">
    <p><input type="file" id="userFile"></p>
</form>

<div id="preview"></div>

【讨论】:

  • 嗨,@istos 先生。我对这种方法有问题 fileReader.readAsDataURL(file);当 html 文件加载到新选项卡或 iframe 中时。无法访问该 html 文件的 cookie。有没有其他方法可以访问该 html 文件的 cookie?
  • 不,这是不可能的,因为这将被视为浏览器中的安全漏洞。一个选项卡/iframe 中的站点无法访问另一个站点的数据。
  • 感谢@istos 先生。顺便说一句,当我尝试通过 jquery 修改加载的 html 的内容时。它给了我这个错误。未捕获的安全错误:阻止了来源为“null”的框架访问来源为“null”的框架。请求访问的帧具有“文件”协议,被访问的帧具有“数据”协议。协议必须匹配。可能是因为 fileReader.readAsDataURL(file);先生,您知道如何修改 iframe 中加载的 html 的内容吗?
  • 请检查我对答案的更新。我认为从这里你可以很好地找出你想自己对代码做的任何事情。如果您有任何其他问题,请打开一个新问题链接到这个问题。
猜你喜欢
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
  • 2016-05-04
  • 2021-03-25
  • 1970-01-01
  • 2016-09-24
  • 2022-11-26
  • 2014-03-01
相关资源
最近更新 更多