Getting specific web page content with CSS stylesheet - javascript

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;
});
};

Related

Injecting scripts via blob is advisable?

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();
}

JS search returned xhr.responseText for div then remove div

I would like to search a xhr.responseText for a div with an id like "something" and then remove all the content from the xhr.responseText contained within that div.
Here is my xhr code:
function getSource(source) {
var url = source[0];
var date = source[1];
/****DEALS WITH CORS****/
var cors_api_host = 'cors-anywhere.herokuapp.com';
var cors_api_url = 'https://' + cors_api_host + '/';
var slice = [].slice;
var origin = self.location.protocol + '//' + self.location.host;
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function () {
var args = slice.call(arguments);
var targetOrigin = /^https?:\/\/([^\/]+)/i.exec(args[1]);
if (targetOrigin && targetOrigin[0].toLowerCase() !== origin &&
targetOrigin[1] !== cors_api_host) {
args[1] = cors_api_url + args[1];
}
return open.apply(this, args);
};
/****END DEALS WITH CORS****/
var xhr = new XMLHttpRequest();
xhr.open("GET", cors_api_url+url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = xhr.responseText;
var respWithoutDiv = removeErroneousData(resp);
}
else{
return "Failed to remove data.";
}
}
xhr.send();
}
remove div here:
/*This must be in JS not JQUERY, its in a web worker*/
function removeErroneousData(resp) {
var removedDivResp = "";
/*pseudo code for removing div*/
if (resp.contains(div with id disclosures){
removedDivResp = resp.removeData(div, 'disclosures');
}
return removedDivResp;
}
You can dump the response in a div and then search for that div you want empty its content.
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = xhr.responseText;
$('div').attr('id', 'resp').html(resp);
$('#resp').find('disclosures').html('');
//var respWithoutDiv = removeErroneousData(resp);
}
else{
return "Failed to remove data.";
}
}

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);
};
});
}

Calling data from JSON file using AJAX

I am trying to load some data from my JSON file using AJAX. The file is called external-file.json. Here is the code, it includes other parts that haven't got to do with the data loading.The part I'm not sure of begins in the getViaAjax funtion. I can't seem to find my error.
function flip(){
if(vlib_front.style.transform){
el.children[1].style.transform = "";
el.children[0].style.transform = "";
} else {
el.children[1].style.transform = "perspective(600px) rotateY(-180deg)";
el.children[0].style.transform = "perspective(600px) rotateY(0deg)";
}
}
var vlib_front = document.getElementById('front');
var el = document.getElementById('flip3D');
el.addEventListener('click', flip);
var word = null; var explanation = null;
var i=0;
function updateDiv(id, content) {
document.getElementById(id).innerHTML = content;
document.getElementById(id).innerHTML = content;
}
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
function counter (index, step){
if (word[index+step] !== undefined) {
index+=step;
i=index;
updateDiv('the-h',word[index]);
updateDiv('the-p',explanation[index]);
}
}
var decos = document.getElementById('deco');
decos.addEventListener('click', function() {
counter(i,-1);
}, false);
var incos = document.getElementById('inco');
incos.addEventListener('click', function() {
counter(i,+1);
}, false);
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
r.onload = function() {
if(this.status < 400 && this.status > 199) {
if(typeof callback === "function")
callback(JSON.parse(this.response));
} else {
console.log("err");// server reached but gave shitty status code}
};
}
r.onerror = function(err) {console.log("error Ajax.get "+url);console.log(err);}
r.send();
}
function yourLoadingFunction(jsonData) {
word = jsonData.words;
explanation = jsonData.explanation;
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
// then call whatever it is to trigger the update within the page
}
getViaAjax("external-file.json", yourLoadingFunction)
As #light said, this:
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
Should be:
function getViaAjax(url, callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", url, true);
I built up a quick sample that I can share that might help you isolate your issue. Stand this up in a local http-server of your choice and you should see JSON.parse(xhr.response) return a javascript array containing two objects.
There are two files
data.json
index.html
data.json
[{
"id":1,
"value":"foo"
},
{
"id":2,
"value":"bar"
}]
index.html
<html>
<head>
</head>
<body onload="so.getJsonStuffs()">
<h1>so.json-with-ajax</h1>
<script type="application/javascript">
var so = (function(){
function loadData(data){
var list = document.createElement("ul");
list.id = "data-list";
data.forEach(function(element){
var item = document.createElement("li");
var content = document.createTextNode(JSON.stringify(element));
item.appendChild(content);
list.appendChild(item);
});
document.body.appendChild(list);
}
var load = function()
{
console.log("Initializing xhr");
var xhr = new XMLHttpRequest();
xhr.onload = function(e){
console.log("response has returned");
if(xhr.status > 200
&& xhr.status < 400) {
var payload = JSON.parse(xhr.response);
console.log(payload);
loadData(payload);
}
}
var uri = "data.json";
console.log("opening resource request");
xhr.open("GET", uri, true);
xhr.send();
}
return {
getJsonStuffs : load
}
})();
</script>
</body>
</html>
Running will log two Javascript objects to the Dev Tools console as well as add a ul to the DOM containing a list item for every object inside the data.json array

load multiple pages from different domain in different divs using javascript

I am trying to load one or more page from different domain inside div of my page on page load. Each page will be loaded in separate div.
I can do this using jquery but I do not want to do this using javascript so that I do not have to add the jquery script as I am not using jquery in my project anywhere.
Below is the jquery code
$(".Widget").each(function () {
var url = $(this).attr("data-url");
$(this).load(url, function (response, status, xhr) {
if (status == "error") {
alert("There was an error: " + xhr.status + " " + xhr.statusText);
}
});
});
I have the equivalent javascript code
var widgets = document.getElementsByClassName('Widget');
for (var i = 0, len = widgets.length; i < len; i++) {
debugger;
var widget = widgets[i];
var xhr = new XMLHttpRequest();
xhr.onload = function () {
widget.innerHTML = this.response;
};
xhr.open('GET', widget.getAttribute("data-url"), true);
xhr.send();
}
But it is displaying only one page in the last div having class Widget.
Following code worked for me
I have created a separate function load
function load(url, element) {
req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
element.innerHTML = req.responseText;
}
and called that function inside a for loop
var widgets = document.getElementsByClassName('Widget');
for(var i = 0, len = widgets.length; i < len; i++) {
var widget = widgets[i];
load(widget.getAttribute("data-url"),widget);
}

Categories