在磁盘上的新浏览器选项卡中使用javascript以编程方式打开html文件

Open an html file programatically using javascript in a new browser tab from disk

本文关键字:javascript 编程 方式打 文件 html 磁盘 浏览器 选项      更新时间:2023-09-26

有没有办法在新选项卡中使用javascript打开html文件?

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

您可以使用文件API。你可以做下面的例子。

这是一个活生生的例子

仅在最新的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>