Safari blob download affects form submit - results in form post getting downloaded instead of opening in new tab

Viewed 379

Download file option (using blob) is present along with another form submit option on a single page. The form result gets downloaded instead of opening in a new tab when download option is selected before form submit.

This happens only in Safari. Rest of the browsers works as expected.

  • Safari version 11.0.1
  • macOS Sierra version 10.12.6

Example jsfiddle - https://jsfiddle.net/e8n9982f/

var $button1 = $("#btn-1");
var $button2 = $("#btn-2");

// Save Locally
$button1.on('click', function() {
  if (typeof(Blob) !== "undefined" && !!new Blob()) {
    var codeToSave = '<!doctype html>' +
      '<html lang="en">' +
      '<head>' +
      '</head>' +
      '<body>' +
      '<h1>Hello, world!</h1>' +
      '</body>' +
      '</html>';

    var codeBlob = new Blob([codeToSave], {
      type: "text/html"
    });
    var codeSaveAsURL = window.URL.createObjectURL(codeBlob);
    var fileNameToSaveAs = "temp-file.html";

    if (window.navigator && window.navigator.msSaveOrOpenBlob) { // For IE, Edge
      window.navigator.msSaveOrOpenBlob(codeBlob, fileNameToSaveAs);
    } else {
      var downloadLink = document.createElement("a");
      downloadLink.download = fileNameToSaveAs;
      downloadLink.href = codeSaveAsURL;
      downloadLink.style.display = "none";
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
    }

    window.URL.revokeObjectURL(codeBlob);
    codeSaveAsURL = null;
    codeBlob = null;
  }

  return false;
});

// Open in JSFiddle
$button2.on('click', function() {
  var form = document.createElement("form");
  form.id = "submitToFiddle";
  form.style.display = "none";
  form.method = "post";
  form.action = "https://jsfiddle.net/api/post/library/pure/";
  form.target = "check";
  //        form.target = "_blank";

  var input = document.createElement("textarea");
  input.name = "html";
  input.innerHTML = '<h1>Fiddle!</h1>';
  document.body.appendChild(form);
  form.appendChild(input);;

  input = document.createElement("input");
  input.type = "submit";
  form.appendChild(input);
  form.submit();
  document.body.removeChild(form);
  return false;
});

To reproduce the issue in Safari, first click on the 'Save Locally' button and then the 'Open in JSFiddle' button.

If 'Open in JSFiddle' button is clicked first and then the 'Save Locally' button, it works as expected.

I am unable to find any reference to why Safari is behaving this way.

1 Answers
Related