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")
Related
I am using xhlhttprequest to load an external html file. However I am trying to figure out how to load only a speicific DIV from that html file.
My external page is helpFile.html- it has dozens header <DIV>s, an each header DIV is a specific help section. On different pages, I want to be able load a specific section? How could I do this? As an example, on the dashboard.html page is a help ? icon, that when the user clicks on it, it will load just the helpFile.html#dashboard section out of the main helpFile.html page - the content would be loaded into a bootstrap modal.
Here is my code to retrieve the entire page, but how can I just retrieve the needed section.
<script>
var request;
function sendInfo() {
var url = "helpFile.html";
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send();
} catch (e) {
alert("Unable to connect to server");
}
}
function getInfo() {
if (request.readyState == 4) {
var val = request.responseText;
document.getElementById('helpModal').innerHTML = val;
}
}
</script>
Use DOMParser and look for the element
if (request.readyState == 4 && request.status == 200) {
var parser = new DOMParser();
var doc = parser.parseFromString(request.responseText;, "text/html");
var dashboardElement = doc.querySelector("#dashboard");
document.getElementById('helpModal').innerHTML = dashboardElement.innerHTML;
}
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'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/
I`am working on a js file which was designed for a home page.
I would like to navigate from this page to other pages via a navigation menu bar.
The target pages are sharing the same templat(a html code), thus for going to a specific page I need to load a specific content, which is saved in a xml file, then pass its contents to the target page.
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.send(null);
}
catch (e) {
window.alert("Unable to load the requested file.");
}
// Until this point I can load the specific content
// How can I get from the url of the target page
// a js document object, so that I can call getElementById(Id)
// to pass the specific content.
// For instance: Im currently opnening X1:= www.main.com
// und I would like to switch to X2 := www.targetpage.com
// target page which contains html the templat.
// The problem **document** represents currently X1
// but i would like to set it to X2 so that I can pass
// the content of xhr.responseText to it
var component = **document**.getElementById(elementId);
component.innerHTML = xhr.responseText;
}
Thanks
Try this, I have added xhr.onload function, which populated text returned from response
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.onload = function () {
var component = document.getElementById(elementId);
component.innerHTML = xhr.responseText;
}
xhr.send(null);
}
catch (e) {
window.alert("Unable to load the requested file.");
}
}
You can also use onreadystatechange event instead of onload. click for more reference
Try this
function loadFileToElement(filename, elementId)
{
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET", filename, false);
xhr.onload = function () {
var com = document.getElementById(elementId);
com.innerHTML = xhr.responseText;
}
xhr.send();
}
catch (e) {
window.alert("Unable to load the requested file.");
}
}
Reference
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