I'm trying to upload a video meanwhile the user navigates through my web application.
To do so, I'm trying to open a new tab in the background with a simple page that includes a new javascript library that just upload the video passing all the parameters it needs.
Right now everything's in 1 library, so I don't see the way I can create that new thread I'm looking for.
Here below I paste the code I'm using:
var blob;
function xhr(url, data, callback) {
'use strict';
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
callback(request.responseText);
}
};
request.open('POST', url);
request.send(data);
}
function sendVideo(name, path) {
'use strict';
var formData = new FormData();
formData.append('filename', name + '.webm');
formData.append('video', blob);
formData.append('title', $('.title').val());
formData.append('tag1', $('#tag1').val());
if ($('#tag2').val()) {
formData.append('tag2', $('#tag2').val());
}
if ($('#tag3').val()) {
formData.append('tag3', $('#tag3').val());
}
xhr(path, formData, function (fName) {
if (fName === 'success') {
window.alert('Your video has been succesfully uploaded');
} else {
window.console.log(fName);
}
});
}
<div onclick="sendVideo(1, 'test');">Send</div>
As well, I'm open for new suggestions about different ways to deal with this problem.
Thanks in advice.
It seems a perfect fit for web workers.
Web workers are a fairly new tool in HTML5 that allows you to "use" multithreading along your pages.
I've used them to acomplish big file loads in the background.
Check this wonderful article from Eric Bidelman on the subject for further info:
http://www.html5rocks.com/en/tutorials/file/filesystem-sync/
Related
I'd like to load inside a QML WebView some HTML, but I need it to be hard-typed (inline). I can't load an external URL nor a local file.
I can't use this:
WebView{
id:webView
url:"file:///android_asset/html/index.html";
}
And I can't use this:
WebView {
id: webView
Component.onCompleted: {
var resource = 'qrc:/path/to/your/resource.html';
var xhr = new XMLHttpRequest;
xhr.open('GET', resource);
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
var response = xhr.responseText;
webView.loadHtml(response);
}
};
xhr.send();
}
}
I specifically need to load it for example like this:
webView.loadHtml("<p>TEST</p>");
Is there any way to achieve it?
Answering my own question.
loadHtml works with inline HTML as long as you also give it a name in the second paramenter, like this:
loadHtml("<p>TEST</p>", "index.html")
Having this API:
http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1
How can I write using pure JS request that downloads me different data after button click event?
All I get from this code is the same quote all the time:
function getQuote (cb) {
var xmlhttp = new XMLHttpRequest();
var quoteURL = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand"
xmlhttp.onreadystatechange = function() {
if (xmlhttp.status == 200 && this.readyState==4) {
cb(this.responseText);
}
};
xmlhttp.open("GET", quoteURL, true);
xmlhttp.send();
}
document.querySelector('button').addEventListener("click", function() {
getQuote(function(quote) {
console.log(quote);
});
})
I tried xmlhttp.abort() and stuff but it didnt want to cooperate.
Thanks in advance!
Your response is being cached by the browser. A common trick to avoid this is to perform a request to
http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&r={random_number}
Notice how the r={random_number} will make the URL different each time.
This is a caching problem. Add a timestamp as a query parameter and you should be able to bust the cache.
I understand that you can set HTTP request headers very easily when making AJAX calls in JavaScript.
However is it also possible to set custom HTTP request headers when inserting an iframe into a page via script?
<iframe src="someURL"> <!-- is there any place to set headers in this? -->
You can make the request in javascript, setting any headers you'd like. Then you can URL.createObjectURL(), to get something suitable for the src of the iframe.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'page.html');
xhr.onreadystatechange = handler;
xhr.responseType = 'blob';
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
// this.response is a Blob, because we set responseType above
var data_url = URL.createObjectURL(this.response);
document.querySelector('#output-frame-id').src = data_url;
} else {
console.error('no pdf :(');
}
}
}
The MIME type of the response is preserved. So if you get an html response, the html will show in the iframe. If you requested a pdf, the browser pdf viewer will kick in for the iframe.
If this is part of a long-lived client-side app, you may want to use URL.revokeObjectURL() to avoid memory leaks.
The object URLs are also pretty interesting. They're of the form blob:https://your.domain/1e8def13-3817-4eab-ad8a-160923995170. You can actually open them in a new tab and see the response, and they're discarded when the context that created them is closed.
Here's a full example: https://github.com/courajs/pdf-poc
No, you can't. However you could set the iframe source to some kind of preload script, which uses AJAX to fetch the actual page with all the headers you want.
As #FellowMD answer is not working on modern browsers due to the depreciation of createObjectURL, I used the same approach but using iframe srcDoc attribute.
Retrieve the content to display in the iframe using XMLHttpRequest or any other method
Set the srcdoc parameter of the iframe
Please find below a React example (I know it is overkill):
import React, {useEffect, useState} from 'react';
function App() {
const [content, setContent] = useState('');
useEffect(() => {
// Fetch the content using the method of your choice
const fetchedContent = '<h1>Some HTML</h1>';
setContent(fetchedContent);
}, []);
return (
<div className="App">
<iframe sandbox id="inlineFrameExample"
title="Inline Frame Example"
width="300"
height="200"
srcDoc={content}>
</iframe>
</div>
);
}
export default App;
Srcdoc is now supported on most browsers. It seems that Edge was a bit late to implement it: https://caniuse.com/#feat=iframe-srcdoc
It turns out that URL.createObjectURL() is deprecated in Chrome 71
(see https://developers.google.com/web/updates/2018/10/chrome-71-deps-rems)
Building on #Niet the dark Absol and #FellowMD's excellent answers, here's how to load a file into an iframe, if you need to pass in authentication headers. (You can't just set the src attribute to the URL):
$scope.load() {
var iframe = #angular.element("#reportViewer");
var url = "http://your.url.com/path/etc";
var token = "your-long-auth-token";
var headers = [['Authorization', 'Bearer ' + token]];
$scope.populateIframe(iframe, url, headers);
}
$scope.populateIframe = function (iframe, url, headers) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'document';
headers.forEach(function (header) {
xhr.setRequestHeader(header[0], header[1]);
});
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
var content = iframe[0].contentWindow ||
iframe[0].contentDocument.document ||
iframe[0].contentDocument;
content.document.open();
content.document.write(this.response.documentElement.innerHTML);
content.document.close();
} else {
iframe.attr('srcdoc', '<html><head></head><body>Error loading page.</body></html>');
}
}
}
}
and shoutout to courajs: https://github.com/courajs/pdf-poc/blob/master/script.js
Is there a way (preferrably using JavaScript) to determine whether a URL is to a SWF or a JPG?
The obvious answer is to sniff the filename for ".jpg" or ".swf" but I'm dealing with banners that are dynamically decided by the server and usually have a lot of parameters and generally don't include an extension.
so i'm wondering if I could load the file first and then read it somehow to determine whether it's SWF or JPG, and then place it, because the JavaScript code I'd need to display a JPG vs a SWF is very different.
Thanks!
You could use javascript to detect if it is a image by creating a dynamic img-tag.
function isImage(url, callback) {
var img = document.createElement('img');
img.onload = function() {
callback(url);
}
img.src = url;
}
And then calling it with:
isImage('http://animals.nationalgeographic.com/staticfiles/NGS/Shared/StaticFiles/animals/images/primary/bald-eagle-head.jpg', function(url) { alert(url + ' is a image'); });
Update
This version will always execute the callback with a boolean value.
function isImage(url) {
var img = document.createElement('img');
img.onload = function() {
isImageCallback(url, true);
}
img.onerror = function() {
isImageCallback(url, false);
}
img.src = url;
}
function isImageCallback(url, result) {
if (result)
alert(url + ' is an image');
else
alert(url + ' is not an image');
}
Put your logic in the isImageCallback function.
I would extend Sijin's answer by saying:
An HTTP HEAD request to the url can be used to examine the resource's mime-type. You
won't need to download the rest of the file that way.
Completely untested, basicly just an idea:
function isImage(url)
{
var http = getHTTPObject();
http.onreadystatechange = function ()
{
if (http.readyState == 4)
{
var contentType = http.getResponseHeader("Content Type");
if (contentType == "image/gif" || contentType == "image/jpeg")
return true;
else
return false;
}
}
http.open("HEAD",url,true);
http.send(null);
}
function getHTTPObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else
{
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
return false;
}
I am not sure the of the exact setup you have, but can you use the HTTP response and check the mime-type to determine image vs flash?
If the URL doesn't have an extension then there is no way to tell without requesting the file from the server.
I need to set/get the cookies stored at first.example while browsing second.example, I have full access of first.example but I only have JavaScript access (can manipulate the DOM as I want) on second.example.
My first approach was to create an iframe on second.example (with JS) that loaded a page like first.example/doAjax?setCookie=xxx and that did an AJAX call to say first.example/setCookie?cookieData=xxx which would set the cookie on first.example with the data we passed around.
That pretty much worked fine for setting the cookie on first.example from second.example - for getting a cookie I basically followed the same procedure, created the iframe that loaded first.example/doAjax?getCookie and that would do an AJAX call to say first.example/getCookie which would read the cookie info on first.example and return it as a JSON object.
The problem is that I'm unable to bring that JSON cookie object back to second.example so I can read it, well maybe I could just bring it when the AJAX call is complete using "window.top" but there's timing issues because its not relative to when the iframe has been loaded. I hope I am clear and was wondering if there's an easier solution rather than this crazy iframe->ajax crap, also seems like this won't even work for getting cookies in SAFARI.
You could inject a script element into HEAD of the document with a callback that passes the cookie you need to whatever function needs it.
Something like:
<script type="text/javascript">
var newfile=document.createElement('script');
newfile.setAttribute("type","text/javascript");
newfile.setAttribute("src", 'http://first.com/doAjax?getCookie&callback=passCookie');
document.getElementsByTagName("head")[0].appendChild(newfile);
</script>
And the page first.com/doAjax?getCookie could do this:
passCookie({'name':'mycookie', 'value':'myvalue'});
Put this PHP-File to first.com:
//readcookie.php
echo $_COOKIE['cookiename'];
On second.com you can use this javascript to get the value:
function readCookieCallback()
{
if ((this.readyState == 4) && (this.status == 200))
{
alert("the value of the cookie is: "+this.responseText);
}
else if ((this.readyState == 4) && (this.status != 200))
{
//error...
}
}
function buttonClickOrAnything()
{
var refreshObject = new XMLHttpRequest();
if (!refreshObject)
{
//IE6 or older
try
{
refreshObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
refreshObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return;
}
}
}
refreshObject.onreadystatechange = readCookieCallback;
refreshObject.open("GET", "http://www.first.com/readcookie.php");
refreshObject.send();
}
Regards,
Robert
For SETTING cookies you can change my script as follows:
The new PHP-Script:
//writecookie.php
setcookie($_GET['c'], $_GET['v']);
And the JavaScript:
function buttonClickOrAnything()
{
var refreshObject = new XMLHttpRequest();
if (!refreshObject)
{
//IE6 or older
try
{
refreshObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
refreshObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return;
}
}
}
refreshObject.open("GET", "http://www.first.com/writecookie.php?c=cookiename&v=cookievalue");
refreshObject.send();
}
That should work on all browsers.