';
doHtml(htm);
}
}
function doTime() {
// need to supply the time!
var digital = new Date();
var hours = digital.getHours();
var minutes = digital.getMinutes();
var seconds = digital.getSeconds();
var amOrPm = "AM";
if (hours > 11) amOrPm = "PM";
if (hours > 12) hours = hours - 12;
if (hours == 0) hours = 12; //0 hour
if (minutes <= 9) minutes = "0" + minutes; //pad with 0
if (seconds <= 9) seconds = "0" + seconds; //pad with 0
var time =" " + hours + ":" + minutes + ":" + seconds + " " + amOrPm +" ";
return time;
}
function doDate() {
// need to supply the date!
var digital = new Date();
var days = digital.getDate();
var months = digital.getMonth()*1 +1;
var years = digital.getFullYear();
var date =" " + days + "/" + months + "/" + years + " " ;
return date;
}
function doTable() {
var rowstext = prompt("enter rows");
var colstext = prompt("enter cols");
var rows = parseInt(rowstext);
var cols = parseInt(colstext);
var table;
if ((rows > 0) && (cols > 0)) {
table = ''
for (var i=0; i < rows; i++) {
table +='';
for (var j=0; j < cols; j++) {
table +=' | ';
}
table +='
';
}
table += '
';
}
return table;
}
function doExport() {
var blob = new Blob([document.getElementById('edit').contentWindow.document.documentElement.outerHTML], { type: 'text/html;charset=utf-8'});
saveAs(blob, document.getElementById('subject').value+'.rtl');
}
function doEdit() {
$.ajax({ url: window.frames[0].location, success: function(data) { window[cfg_editorname].contentWindow.document.write(data); } });
}
function doBreak(){
var t='
'
return t;
}
function viewsource(source) {
// load the html into a variable, blank the body, import as text, disable gui
var html;
if (isIE()){
html=window[cfg_editorname].document.body.innerHTML ; //if browser supports M$ conventions
alert(html) ; //load into an alert as importnode not supported by IE
return;
}
if (source) {
html = document.createTextNode(jQuery().restoreImagePaths(document.getElementById('edit').contentWindow.document.body.innerHTML));
document.getElementById(cfg_editorname).contentWindow.document.body.innerHTML = "";
html = document.getElementById(cfg_editorname).contentWindow.document.importNode(html,false);
document.getElementById(cfg_editorname).contentWindow.document.body.appendChild(html);
document.getElementById("control1").style.visibility="hidden";
document.getElementById("control2").style.visibility="hidden";
document.getElementById("control3").style.visibility="hidden";
document.getElementById("control4").style.visibility="hidden";
} else {
html = document.getElementById(cfg_editorname).contentWindow.document.body.ownerDocument.createRange();
html.selectNodeContents(document.getElementById(cfg_editorname).contentWindow.document.body);
document.getElementById(cfg_editorname).contentWindow.document.body.innerHTML = jQuery().convertImagePaths(html.toString());
document.getElementById("control1").style.visibility="visible";
document.getElementById("control2").style.visibility="visible";
document.getElementById("control3").style.visibility="visible";
document.getElementById("control4").style.visibility="visible";
}
return;
}
function usecss(source) {
if (isIE()){
//if browser supports M$ conventions it may error on this execCommand
return;
}
// a Mozilla only feature
document.getElementById('edit').contentWindow.document.execCommand("styleWithCSS", false, (source));
}
// end of traditional editControl.js functions
// page loading
function addJavascript(jsname,pos) {
var th = document.getElementsByTagName(pos)[0];
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src',jsname);
th.appendChild(s);
}
jQuery(document).ready(function(){
if (jQuery.fn.convertImagePaths === undefined) {
addJavascript("../share/javascript/eforms/imageControl.js", "head");
}
});
function popup(location) {
DocPopup = window.open(location,"_blank","height=380,width=580");
if (DocPopup != null) {
if (DocPopup.opener == null) {
DocPopup.opener = self;
}
}
}
function gup(name, url) {
if (url == null) { url = window.location.href; }
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if (results == null) { return ""; }
else { return results[1]; }
}
var demographicNo ="";
jQuery(document).ready(function(){
demographicNo = gup("demographic_no");
if (demographicNo == "") { demographicNo = gup("efmdemographic_no", jQuery("form").attr('action')); }
if (typeof signatureControl != "undefined") {
signatureControl.initialize({
sigHTML:"../signature_pad/tabletSignature.jsp?inWindow=true&saveToDB=true&demographicNo=",
demographicNo:demographicNo,
refreshImage: function (e) {
var html = "";
doHtml(html);
},
signatureInput: "#signatureInput"
});
}
});
var cache = createCache({
defaultCacheResponseHandler: function(type) {
if (checkKeyResponse(type)) {
doHtml(cache.get(type));
}
},
cacheResponseErrorHandler: function(xhr, error) {
alert("Please contact an administrator, an error has occurred.");
}
});
function checkKeyResponse(response) {
if (cache.isEmpty(response)) {
alert("The requested value has no content.");
return false;
}
return true;
}
function printKey (key) {
var value = cache.lookup(key);
if (value != null && checkKeyResponse(key)) { doHtml(cache.get(key)); }
}
function submitFaxButton() {
document.getElementById('faxEForm').value=true;
saveRTL();
setTimeout('document.RichTextLetter.submit()',1000);
}
cache.addMapping({name: "template", cacheResponseHandler: populateTemplate});
// add RTL specific key values
// each cache name is an array of key values
// no need to add for standard apconfig.xml tags
// format text for instant access
cache.addMapping({
name: "letterhead",
values: ["clinic_name", "clinic_fax", "clinic_phone", "clinic_addressLineFull", "doctor", "doctor_contact_phone", "doctor_contact_fax", "doctor_contact_addr","current_user"],
storeInCacheHandler: function (key, value) {
var text = genericLetterhead();
cache.put("letterhead", text);
},
cacheResponseHandler: function () {
if (checkKeyResponse(this.name)) {
doHtml(cache.get(this.name));
}
}
});
cache.addMapping({
name: "_ReferringBlock",
values: ["referral_name", "referral_address", "referral_phone", "referral_fax"],
storeInCacheHandler: function (key, value) {
var text =
(!cache.isEmpty("referral_name") ? cache.get("referral_name") + "
" : "")
+ (!cache.isEmpty("referral_address") ? cache.get("referral_address") + "
" : "")
+ (!cache.isEmpty("referral_phone") ? "Tel: " + cache.get("referral_phone") + "
" : "")
+ (!cache.isEmpty("referral_fax") ? "Fax: " + cache.get("referral_fax") + "
" : "");
if (text == "") {
text =
(!cache.isEmpty("bc_referral_name") ? cache.get("bc_referral_name") + "
" : "")
+ (!cache.isEmpty("bc_referral_address") ? cache.get("bc_referral_address") + "
" : "")
+ (!cache.isEmpty("bc_referral_phone") ? "Tel: " + cache.get("bc_referral_phone") + "
" : "")
+ (!cache.isEmpty("bc_referral_fax") ? "Fax: " + cache.get("bc_referral_fax") + "
" : "");
}
cache.put(this.name, text)
},
cacheResponseHandler: function () {
if (checkKeyResponse(this.name)) {
doHtml(cache.get(this.name));
}
}
});
// fudge for older apconfig.xml that lack referal_first_name, patient_nameF etc
cache.addMapping({
name: "referral_nameF",
values: ["referral_name"],
storeInCacheHandler: function(_key,_val) {
if (!cache.isEmpty("referral_name")) {
var mySplitResult = cache.get("referral_name").toString().split(",");
cache.put("referral_nameF", mySplitResult[1]);
}
}
});
cache.addMapping({
name: "referral_nameL",
values: ["referral_name"],
storeInCacheHandler: function(_key,_val) {
if (!cache.isEmpty("referral_name")) {
var mySplitResult = cache.get("referral_name").toString().split(",");
cache.put("referral_nameL", mySplitResult[0]);
}
}
});
cache.addMapping({
name: "PatientNameF",
values: ["first_last_name"],
storeInCacheHandler: function(_key,_val) {
if (!cache.isEmpty("first_last_name")) {
var mySplitResult = cache.get("first_last_name").toString().split(",");
cache.put("PatientNameF", mySplitResult[0]);
}
}
});
cache.addMapping({
name: "_age",
values: ["age","ageComplex"],
storeInCacheHandler: function(_key,_val) {
if (!cache.isEmpty("ageComplex")) {
cache.put("_age", cache.get("ageComplex"));
} else {
cache.put("_age", cache.get("age")+" year old");
}
}
});
// end fudge
cache.addMapping({
name: "_ReferringBlockLite",
values: ["referral_name", "referral_address"],
storeInCacheHandler: function(key,value) {
var text =
(!cache.isEmpty("referral_name") ? cache.get("referral_name") + "
" : "")
+ (!cache.isEmpty("referral_address") ? cache.get("referral_address") + "
" : "")
cache.put(this.name, text)
},
cacheResponseHandler: function () {
if (checkKeyResponse(this.name)) {
doHtml(cache.get(this.name));
}
}
});
cache.addMapping({
name: "_SocialFamilyHistory",
values: ["social_family_history"],
storeInCacheHandler: function(key,value) {
var text = cache.get("social_family_history").replace(/(
)+/g,"
");
cache.put(this.name, text );
},
cacheResponseHandler:function () {
if (checkKeyResponse(this.name)) {
doHtml(cache.get(this.name));
}
}
});
cache.addMapping({
name: "medical_historyS",
values: ["medical_history"],
storeInCacheHandler: function(_key,_val) {
if (!cache.isEmpty("medical_history")) {
var mySplitResult = cache.get("medical_history").toString().split("]]-----");
cache.put("medical_historyS", mySplitResult.pop());
}
}
});
cache.addMapping({
name: "_ClosingSalutation",
values: ["provider_name_first_init", "current_user_fname_lname", "doctor", "current_user"],
storeInCacheHandler: function (key,value) {
var imgsrc=pickStamp();
var frag = ("Yours Sincerely
" + imgsrc + "
");
var salutation = frag;
if (!cache.isEmpty("provider_name_first_init")) {
salutation=(frag+cache.get("provider_name_first_init") + ", MD");
}
// now allow for signing by the current user
if (cache.contains("current_user")) {
for (i=0; i=0){
console.log('current user has a signature so use it in the closing salutation');
salutation=(frag+cache.get("current_user_fname_lname") + ", MD");
}
}
}
cache.put(this.name, salutation);
},
cacheResponseHandler:function () {
if (checkKeyResponse(this.name)) {
doHtml(cache.get(this.name));
}
}
});
cache.addMapping({
name: "stamp",
values: ["stamp_name", "doctor", "current_user"],
storeInCacheHandler: function(_key,_val) {
var imgsrc=pickStamp();
cache.put("stamp",imgsrc);
}
});
// code that loads hidden text to cache
$('input:hidden').each(function() {
var value = $(this).val();
cache.put(this.name, value);
});
// Setting up many to one mapping for derived gender keys.
var genderKeys = ["he_she", "his_her", "gender"];
var genderIndex;
for (genderIndex in genderKeys) {
cache.addMapping({ name: genderKeys[genderIndex], values: ["sex"]});
}
cache.addMapping({name: "sex", values: ["sex"], storeInCacheHandler: populateGenderInfo});
function isGenderLookup(key) {
var y;
for (y in genderKeys) { if (genderKeys[y] == key) { return true; } }
return false;
}
// Valid gender codes include F M O T U and empty
function populateGenderInfo(key, val){
switch (val){
case 'F':
cache.put("sex", "F");
cache.put("he_she", "she");
cache.put("his_her", "her");
cache.put("gender", "female");
break;
case 'M':
cache.put("sex", "M");
cache.put("he_she", "he");
cache.put("his_her", "his");
cache.put("gender", "male");
break;
case 'O':
break;
cache.put("sex", "O");
cache.put("he_she", "they");
cache.put("his_her", "their");
cache.put("gender", "genderqueer");
break;
case 'T':
cache.put("sex", "T");
cache.put("he_she", "they");
cache.put("his_her", "their");
cache.put("gender", "trans gender");
break;
default:
cache.put("sex", "X");
cache.put("he_she", "they");
cache.put("his_her", "their");
cache.put("gender", "unspecified gender");
}
}
function Start() {
$.ajax({
url : "efmformrtl_templates.jsp",
success : function(data) {
$("#template").html(data);
loadDefaultTemplate();
}
});
$(".cacheInit").each(function() {
cache.put($(this).attr('name'), $(this).val());
$(this).remove();
});
// set eventlistener for the iframe to flag changes in the text displayed
var agent = navigator.userAgent.toLowerCase(); //for non IE browsers
if ((agent.indexOf("msie") == -1) || (agent.indexOf("opera") != -1)) {
document.getElementById(cfg_editorname).contentWindow
.addEventListener('keypress', setDirtyFlag, true);
}
// set the HTML contents of this edit control from the value saved in OSCAR (if any)
var contents = document.getElementById('Letter').value
if (contents.length == 0) {
parseTemplate();
} else {
seteditControlContents(cfg_editorname, contents);
// seteditControlContents(cfg_editorname, decodeURIComponent(contents));
document.getElementById(cfg_editorname).contentWindow.document.designMode = 'on';
}
maximize();
console.log('updating attached');
updateAttached();
}
function htmlLine(text) {
return text.replace(/\r?\n/g,"
");
}
function genericLetterhead() {
// set the HTML contents of the letterhead
var address = ''
+ cache.get('clinic_name')
+ ' |
'
+ cache.get('doctor_contact_addr')
+ ' Fax: ' + cache.get('doctor_contact_fax')
+ ' Phone: ' + cache.get('doctor_contact_phone')
+ '
|
';
if ( (cache.get('clinic_name').toLowerCase()).indexOf('amily health team',0)>-1){
address=fhtLetterhead(); }
if ( (cache.get('clinic_name').toLowerCase()).indexOf('fht',0)>-1){
address=fhtLetterhead(); }
return address;
}
function fhtLetterhead() {
// set the HTML contents of the letterhead using FHT colours
var address = cache.get('clinic_addressLineFull')
+ '
Fax:' + cache.get('clinic_fax')
+ ' Phone:' + cache.get('clinic_phone');
// use the doctors name to allow for a secretary to write a letter under direction
if (cache.contains("doctor")) {
var str = cache.get('doctor');
var res = str.split(", "); //last, first
console.log("doctor="+res[0]);
}
// use the current user instead if they have a signature on file
if (cache.contains("current_user")) {
var str = cache.get('current_user');
console.log(str);
for (i=0; i=0){
console.log('current user '+str+' has a signature so use their name');
var str = cache.get('current_user');
var res = str.split(", "); //last, first
}
}
}
address = ''
+ cache.get('clinic_name')
+ '
|
'
+ res[1] + " " + res[0] + ' |
'
+ address + ' |
';
return address;
}
function pickStamp() {
// set the HTML contents of the signature stamp
// for single user set stamp.png to be that users signature image in the images folder
// otherwise form a stamp.js file and upload to images with content as below
// defining key value pairs of name of doctor and the corresponding image file
// var ImgArray = [
// "doctor|SignatureFile.png",
// ];
var mystamp ='';
if (cache.contains("doctor")) {
for (i=0; i=0){
mystamp = '';
}
}
}
// now allow for signing by the current user
if (cache.contains("current_user")) {
for (i=0; i=0){
console.log('current user has a signature so use it');
mystamp = '';
}
}
}
return mystamp;
}
var formIsRTL = true;
// lab_grid2.js //
var elements = (window.location.pathname.split('/', 2))
firstElement = (elements.slice(1))
vPath = ("https://" + location.host + "/" + firstElement)
//alert(vPath)
//get parameters
var params = {};
if (location.search) {
var parts = location.search.substring(1).split('&');
for (var i = 0; i < parts.length; i++) {
var nv = parts[i].split('=');
if (!nv[0]) continue;
params[nv[0]] = nv[1] || true;
}
}
// probably wrong fid TODO
var formPath = vPath + "/eform/efmshowform_data.jsp?fid=74&LabName="
var measureArray = [];
var measureDateArray = [];
function getMeasures(measure, max) {
xmlhttp = new XMLHttpRequest();
var pathArray = window.location.pathname.split('/');
var newURL = "..//oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?type=" + measure;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var str = xmlhttp.responseText; //local variable
if (!str) {
return;
}
var myRe = /([\S,\d,\.]+)<\/td>/g; //for the measurement
var myArray;
measureArray = []
measureDateArray = []
var i = 0;
while ((myArray = myRe.exec(str)) !== null) {
measureArray[i] = myArray[1];
i = i + 1;
}
var myRe = / | ([0-9,-]+)<\/td>\s* | /g; //the first date is the observation date
var myArray;
var i = 0;
while ((myArray = myRe.exec(str)) !== null) {
measureDateArray[i] = myArray[1];
i = i + 1;
}
}
}
xmlhttp.open("GET", newURL, false);
xmlhttp.send();
//alert(this.patient_name.value)
if (measureArray.length > 0) {
//myGraphWindow = "" + measure + ": " + ""
myGraphWindow = measure + ": "
//myGraphWindow = formPath + measure + measureArray + measureDateArray + measure + ": "
doHtml(""+myGraphWindow +"");
displaynum = measureArray.length
if (measureArray.length > max) {
displaynum = max
}
for (jj = 0; jj < displaynum; jj++) {
var d = new Date(measureDateArray[jj])
var LabDate = "(" + d.getFullYear() + "/" + (d.getMonth() + 1) + "); "
doHtml(""+measureArray[jj].bold()+ ""+""+LabDate+ "")
}
doHtml(" ");
}
}
// end lab grid //
function collapseFooter() {
document.getElementById('arrow').classList.toggle('chevron');
document.getElementById('controls4').classList.toggle('hide');
console.log('changing from existing height of '+$('#edit').prop('style')['height']+' to ');
if ($('#edit').prop('style')['height'] == cfg_height+'px'){
$('#edit').css({height: '830px'});
} else {
$('#edit').css({height: (cfg_height+'px')});
}
console.log($('#edit').prop('style')['height']);
}
//-- Autocomplete script --
var searchDropDownFlag = false;
function consultantSearch(term) {
if (term.length < 2) {
document.getElementById('tempBin').innerHTML = "You must enter at least 2 characters of a patients name!";
return false;
}
tmpBin = document.getElementById('tempBin');
loaderImg(tmpBin);
var request = new XMLHttpRequest();
//professionalSpecialists 2020-Nov-04
//request.open('GET', '../oscarEncounter/oscarConsultationRequest/searchprofessionalSpecialists.json?keyword=' + term, true);
request.open('GET', '../oscarEncounter/oscarConsultationRequest/searchProfessionalSpecialist.json?keyword='+term, true);
request.setRequestHeader("Content-Type", "application/json");
request.onload = function() {
var data = this.response;
var results_html = "";
if (request.status >= 200 && request.status < 400) {
// Request finished. Do processing here.
var data = JSON.parse(this.response);
var results_html = "";
if (data.length > 0) {
results_html += "";
for (i = 0; i <= data.length - 1; i++) {
results_html += "- " + data[i].lastName + ", " + data[i].firstName + "
";
}
results_html += " ";
} else {
results_html = "No results found matching " + term + ".";
}
//ensure the loader has time to display
setTimeout(() => {
document.getElementById('tempBin').innerHTML = results_html;
}, 500);
} else {
console.log('error')
}
} // end onload
request.send();
}
function populateInputField(el, type) {
document.getElementById("referral_name").value = el.firstChild.data;
if (type == "consultant")
document.getElementById("consultantFilter").value = el.getAttribute("data-id").trim();
//populate address: possible names = referral_address
document.getElementById("CopyTo").value = el.getAttribute("data-address").trim();
searchDropDownFlag = false;
toggleTempBin(0, null);
}
function toggleTempBin(a, parentElement) {
if (a === 1) {
position = getOffset(document.getElementById(parentElement));
new_top = position.top + document.getElementById(parentElement).offsetHeight
new_left = position.left - 10;
document.getElementById("tempBin").style.top = "58px";
document.getElementById("tempBin").style.left = "-2px";
document.getElementById("tempBin").style.width = document.getElementById(parentElement).offsetWidth + "px";
document.getElementById("tempBin").style.display = 'block';
} else if (a === 0 && searchDropDownFlag === false) {
document.getElementById("tempBin").style.display = 'none';
document.getElementById("tempBin").innerHTML = "You must enter at least 2 characters of a patients name!";
}
}
function getOffset(el) {
var _x = 0;
var _y = 0;
while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return {
top: _y,
left: _x
};
}
function loaderImg(bin) {
bin.innerHTML = "";
var img = document.createElement('img');
img.src = '../images/loader.gif';
img.style.marginLeft = "40%";
bin.appendChild(img);
}
function tempBinHover(h) {
if (h) {
searchDropDownFlag = true;
} else {
searchDropDownFlag = false;
}
}
// filesaver.js
/*
* FileSaver.js
* A saveAs() FileSaver implementation.
*
* By Eli Grey, http://eligrey.com
*
* License : https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md (MIT)
* source : http://purl.eligrey.com/github/FileSaver.js
*/
/*
//Paste this code to saveAs
var blob = new Blob([$("html").html()], {
type: "text/html;charset=utf-8"
});
saveAs(blob, "page.html");
}
*/
// The one and only way of getting global scope in all environments
// https://stackoverflow.com/q/3277182/1008999
var _global = typeof window === 'object' && window.window === window
? window : typeof self === 'object' && self.self === self
? self : typeof global === 'object' && global.global === global
? global
: this
function bom (blob, opts) {
if (typeof opts === 'undefined') opts = { autoBom: false }
else if (typeof opts !== 'object') {
console.warn('Deprecated: Expected third argument to be a object')
opts = { autoBom: !opts }
}
// prepend BOM for UTF-8 XML and text/* types (including HTML)
// note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
if (opts.autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
return new Blob([String.fromCharCode(0xFEFF), blob], { type: blob.type })
}
return blob
}
function download (url, name, opts) {
var xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'blob'
xhr.onload = function () {
saveAs(xhr.response, name, opts)
}
xhr.onerror = function () {
console.error('could not download file')
}
xhr.send()
}
function corsEnabled (url) {
var xhr = new XMLHttpRequest()
// use sync to avoid popup blocker
xhr.open('HEAD', url, false)
try {
xhr.send()
} catch (e) {}
return xhr.status >= 200 && xhr.status <= 299
}
// `a.click()` doesn't work for all browsers (#465)
function click (node) {
try {
node.dispatchEvent(new MouseEvent('click'))
} catch (e) {
var evt = document.createEvent('MouseEvents')
evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80,
20, false, false, false, false, 0, null)
node.dispatchEvent(evt)
}
}
// Detect WebView inside a native macOS app by ruling out all browsers
// We just need to check for 'Safari' because all other browsers (besides Firefox) include that too
// https://www.whatismybrowser.com/guides/the-latest-user-agent/macos
var isMacOSWebView = /Macintosh/.test(navigator.userAgent) && /AppleWebKit/.test(navigator.userAgent) && !/Safari/.test(navigator.userAgent)
var saveAs = _global.saveAs || (
// probably in some web worker
(typeof window !== 'object' || window !== _global)
? function saveAs () { /* noop */ }
// Use download attribute first if possible (#193 Lumia mobile) unless this is a macOS WebView
: ('download' in HTMLAnchorElement.prototype && !isMacOSWebView)
? function saveAs (blob, name, opts) {
var URL = _global.URL || _global.webkitURL
var a = document.createElement('a')
name = name || blob.name || 'download'
a.download = name
a.rel = 'noopener' // tabnabbing
// TODO: detect chrome extensions & packaged apps
// a.target = '_blank'
if (typeof blob === 'string') {
// Support regular links
a.href = blob
if (a.origin !== location.origin) {
corsEnabled(a.href)
? download(blob, name, opts)
: click(a, a.target = '_blank')
} else {
click(a)
}
} else {
// Support blobs
a.href = URL.createObjectURL(blob)
setTimeout(function () { URL.revokeObjectURL(a.href) }, 4E4) // 40s
setTimeout(function () { click(a) }, 0)
}
}
// Use msSaveOrOpenBlob as a second approach
: 'msSaveOrOpenBlob' in navigator
? function saveAs (blob, name, opts) {
name = name || blob.name || 'download'
if (typeof blob === 'string') {
if (corsEnabled(blob)) {
download(blob, name, opts)
} else {
var a = document.createElement('a')
a.href = blob
a.target = '_blank'
setTimeout(function () { click(a) })
}
} else {
navigator.msSaveOrOpenBlob(bom(blob, opts), name)
}
}
// Fallback to using FileReader and a popup
: function saveAs (blob, name, opts, popup) {
// Open a popup immediately do go around popup blocker
// Mostly only available on user interaction and the fileReader is async so...
popup = popup || open('', '_blank')
if (popup) {
popup.document.title =
popup.document.body.innerText = 'downloading...'
}
if (typeof blob === 'string') return download(blob, name, opts)
var force = blob.type === 'application/octet-stream'
var isSafari = /constructor/i.test(_global.HTMLElement) || _global.safari
var isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent)
if ((isChromeIOS || (force && isSafari) || isMacOSWebView) && typeof FileReader !== 'undefined') {
// Safari doesn't allow downloading of blob URLs
var reader = new FileReader()
reader.onloadend = function () {
var url = reader.result
url = isChromeIOS ? url : url.replace(/^data:[^;]*;/, 'data:attachment/file;')
if (popup) popup.location.href = url
else location = url
popup = null // reverse-tabnabbing #460
}
reader.readAsDataURL(blob)
} else {
var URL = _global.URL || _global.webkitURL
var url = URL.createObjectURL(blob)
if (popup) popup.location = url
else location.href = url
popup = null // reverse-tabnabbing #460
setTimeout(function () { URL.revokeObjectURL(url) }, 4E4) // 40s
}
}
)
_global.saveAs = saveAs.saveAs = saveAs
if (typeof module !== 'undefined') {
module.exports = saveAs;
}
|