Injecting scripts via blob is advisable? - javascript

Am trying to download the javascript files through web workers by using XHR and injecting to body via blob URL. Is it advisable of doing it ?
Sample code:
var worker = "https://wrapperbi.com/worker/worker.js";
let scriptWrappers = 'importScripts(\'' + worker + '\')', //No I18N
workerPaths = window.URL.createObjectURL(new Blob([scriptWrappers])),
dataObj = {'responseType':'blob', 'requestURL': "https://wrapperbi.com/js/manifest.js"};
let assetsWorkerss = new Worker(workerPaths);
assetsWorkerss.postMessage(dataObj);
assetsWorkerss.onmessage = function (event) {
var script = document.createElement('script'),
src = URL.createObjectURL(event.data);
script.src = src;
document.body.appendChild(script);
worker file sample code:
onmessage = function (event) {
var requestType = event.data.requestType ? event.data.requestType : 'GET',
isAsync = typeof event.data.isAsync === "undefined" ? true : event.data.isAsync,
responseType = event.data.responseType ? event.data.responseType : 'json',
xhr = new XMLHttpRequest();
xhr.open(requestType, event.data.requestURL, isAsync);
xhr.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200){
postMessage(this.response);
}
};
xhr.onerror = function () {
postMessage(this.status);
};
xhr.responseType = responseType;
if(event.data.isCrossDomain) {
xhr.withCredentials = event.data.isCrossDomain;
}
xhr.send();
}

Related

Download multiple files with XmlHttpRequests

I'm trying to download multiple files with XmlHttpRequest, but can't deal with async method. How can I get my result in same sequence as urls array.
urls = ['url1', 'url2', 'url3']
getting result:
['url2', 'url1', 'url3']
function downloadFiles(urls, callback) {
var buffer = []
var ind = 0
for (var u in urls) {
var xhr = new XMLHttpRequest()
xhr.open('GET', urls[u], true)
xhr.responseType = 'arraybuffer'
xhr.onload = function (e) {
if (this.status == 200 || this.status == 304) {
var uInt8Array = new Uint8Array(this.response)
var i = uInt8Array.length
var binaryString = new Array(i)
while (i--)
binaryString[i] = String.fromCharCode(uInt8Array[i])
var data = binaryString.join('')
var base64 = window.btoa(data)
var fileName = urls[ind].substr(urls[ind].indexOf('.jpg')-20, 24)
//var downloadedFile = createTempFolder() + fileName;
//writeFile(downloadedFile, base64)
buffer[ind] = downloadedFile
if (ind === urls.length - 1) {
return callback(buffer)
}
ind++
}
};
xhr.send()
}
}

How to receive binary file as response and render file using javascript?

enter image description hereWe have a service that interacts with box.com and returns a file in binary format.
I am trying to hit that service from java-script to get binary file and render/dowload as actual file using below code but no response is being received (I have verified that service is returning the response).
Console logs are blank.
Any help is greatly appreciated.
<h1>File Download</h1>
<button type="button" onclick="loadDoc()">Download</button>
<p id="demo"></p>
function loadDoc() {
var xhr = new XMLHttpRequest();
xhr.open('POST', URL, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Authorization", "Basic xxcxcsdfdfdferererer=");
//xhr.setRequestHeader("Access-Control-Allow-Origin", true);
xhr.responseType = 'arraybuffer';
xhr.send(JSON.stringify({projects: [{id: "xxxxxx", fileId: "1234456566"}]}));
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status === 200) {
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
var type = xhr.getResponseHeader('Content-Type');
var blob = typeof File === 'function' ? new File([this.response], filename, { type: type }) : new Blob([this.response], { type: type });
if (typeof window.navigator.msSaveBlob !== 'undefined') {
// IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
window.navigator.msSaveBlob(blob, filename);
} else {
var URL = window.URL || window.webkitURL;
var downloadUrl = URL.createObjectURL(blob);
if (filename) {
// use HTML5 a[download] attribute to specify filename
var a = document.createElement("a");
// safari doesn't support this yet
if (typeof a.download === 'undefined') {
window.location = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function () { URL.revokeObjectURL(downloadUrl); }, 100); // cleanup
}
}
};
}

Getting specific web page content with CSS stylesheet

I have this code which gets a specific web page content and loads it in an iframe. It works fine, unfortunately this content is in the body and doesn't come with CSS formatting, so I get an unformatted page. How can I get the stylesheet to come with the page content?
Thanks in advance!
var getHTML = function (url, callback) {
if (!window.XMLHttpRequest) return;
var xhr = new XMLHttpRequest();
xhr.onload = function () {
if (callback && typeof (callback) === 'function') {
callback(this.responseXML);
}
}
xhr.open('GET', url);
xhr.responseType = 'document';
xhr.send();
};
function loadFram() {
var src = document.getElementById("opt1").value;
getHTML(src, function (response) {
var x = document.getElementById("frame1");
var y = (x.contentWindow || x.contentDocument);
if (y.document)y = y.document;
y.body.innerHTML = response.documentElement.querySelector('[id="Container"]').innerHTML;
});
};

Error while trying to play webm with MSE,chunks not appending , video stopping

I want to play webm whose duration is >5s (1.32 mins)
this webm.
I'have been trying to modify this example, when I run it, chunks are not appending and video stops at some point, and I'm getting this error:
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
sourceBuffer.appendBuffer(new Uint8Array(e.target.result));
Could someone clarify please?
<script>
var FILE = 'test2.webm'; //that webm
var NUM_CHUNKS = 10;
var video = document.querySelector('video');
window.MediaSource = window.MediaSource || window.WebKitMediaSource;
if (!!!window.MediaSource) {
alert('MediaSource API is not available');
}
var mediaSource = new MediaSource();
//document.querySelector('[data-num-chunks]').textContent = NUM_CHUNKS;
video.src = window.URL.createObjectURL(mediaSource);
function callback(e) {
var sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vorbis,vp8"');
logger.log('mediaSource readyState: ' + this.readyState);
GET(FILE, function(uInt8Array) {
var file = new Blob([uInt8Array], {
type: 'video/webm'
});
var chunkSize = Math.ceil(file.size / NUM_CHUNKS);
logger.log('num chunks:' + NUM_CHUNKS);
logger.log('chunkSize:' + chunkSize + ', totalSize:' + file.size);
// Slice the video into NUM_CHUNKS and append each to the media element.
var i = 0;
(function readChunk_(i) {
var reader = new FileReader();
// Reads aren't guaranteed to finish in the same order they're started in,
// so we need to read + append the next chunk after the previous reader
// is done (onload is fired).
reader.onload = function(e) {
sourceBuffer.appendBuffer(new Uint8Array(e.target.result));
logger.log('appending chunk:' + i);
if (i == NUM_CHUNKS - 1) {
mediaSource.endOfStream();
} else {
if (video.paused) {
video.play(); // Start playing after 1st chunk is appended.
}
readChunk_(++i);
}
};
var startByte = chunkSize * i;
var chunk = file.slice(startByte, startByte + chunkSize);
reader.readAsArrayBuffer(chunk);
})(i); // Start the recursive call by self calling.
});
}
mediaSource.addEventListener('sourceopen', callback, false);
mediaSource.addEventListener('webkitsourceopen', callback, false);
mediaSource.addEventListener('webkitsourceended', function(e) {
logger.log('mediaSource readyState: ' + this.readyState);
}, false);
function GET(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.send();
xhr.onload = function(e) {
if (xhr.status != 200) {
alert("Unexpected status code " + xhr.status + " for " + url);
return false;
}
callback(new Uint8Array(xhr.response));
};
}
</script>
<script>
function Logger(id) {
this.el = document.getElementById('log');
}
Logger.prototype.log = function(msg) {
var fragment = document.createDocumentFragment();
fragment.appendChild(document.createTextNode(msg));
fragment.appendChild(document.createElement('br'));
this.el.appendChild(fragment);
};
Logger.prototype.clear = function() {
this.el.textContent = '';
};
var logger = new Logger('log');
</script>
<script>
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-22014378-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script');
ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
Your video is working well in my player based on example you provided. I do not call mediaSource.endOfStream(); and i am not slicing file using FileReader class (useless).
Use Range http header to get slices from you webserver directly.
Example:
function GET(url, from = 0, to = '') {
return new Promise((accept, reject) => {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.setRequestHeader("Range", `bytes=${from}-${to}`);
xhr.send();
xhr.onload = function(e) {
if (xhr.status != 200 && xhr.status != 206) {
alert("Unexpected status code " + xhr.status + " for " + url);
reject(e);
}
accept(xhr.response);
};
});
}

Blob Url obtained from URL.createObjectUrl(mediastream) returns HTTP 404

I'm trying to get a MediaStream object into a blob, but I have some problems.
This is the part of my script for the UserMedia component:
var mediastream = undefined;
var blob = undefined;
var video = document.getElementById('test');
This is my script where I'm trying my test:
var mediastream = undefined;
var blobUrl = undefined;
var video = document.getElementById('test');
function successCallback (stream) {
mediastream = stream;
blobUrl = URL.createObjectURL(mediastream);
var xhr = new XMLHttpRequest();
xhr.open('GET', blobUrl, true);
xhr.responseType = 'arraybuffer';
xhr.withCredentials = true;
xhr.onreadystatechange = function () {
console.log('xhr.readyState='+xhr.readyState);
if (xhr.readyState !== 4) {
return;
} else {
var myBlob = this.response;
}
function errorCallback (stream) {
console.log('error');
}
Setting the blobUrl to the video.src I don't have any problem:
video.src = blobUrl; <- WORKS
But if I call the urlBob url (like this one: blob:http%3A//localhost%3A8080/b1ffa5b7-c0cc-4acf-8890-f5d0f08de9cb ) I obtain HTTP status 404.
For sure there is something wrong on my implementation.
Any suggestions?
Thank you!

Categories