Load Local HTML Into Div (Chrome Extension) - javascript

I'm not using a framework and I want to implement an architecture whereby a single html file holds the skeleton of my layout, and certain other html snippets are loaded into various divs in that layout. The code is all in the same directory location inside my main extension folder /popup/
I want to build a very simple function to load the locally saved html snippets into the div elements. Here is my first attempt:
function loadView(viewName,destination){
var URL = "/popup/"+viewName;
var client = new XMLHttpRequest();
client.open('GET', URL, false);
client.onreadystatechange = function() {
document.getElementById(destination).innerHTML = client.responseText;
}
client.send();
}
// Example of a call
loadView('contact.html','widgetBox');
Obviously this is terrible because it relies on setting the ajax to asynch false. But under this solution, that is necessary because the next line of code in the script may/does try to manipulate the newly loaded content.
What would be a method for reaching a similar result, that does not depend on ajax? (or at least, which would resolve the need to use asynch false)
Notes:
I know that there are frameworks for basically this exact problem. I like to learn how to do things without frameworks. I am not challenging the use of frameworks, I'm just not interested in those approaches in this question. Relatedly, I'd like to avoid using jquery (and as this is a chrome extension, developing in clean JS isn't particularly painful).
The content of contact.html is some html, is just a string of html, (i.e. it does not have a header or any content besides that which I seek to load). I am open to another convention besides discrete .html files, but I like this convention as it is easy to keep my various page chunks organized, and keeping them as .html files allows me to read them easily in things that format html nicely.

You should have your loadView function accept a callback as a third parameter. Then, call it when the Ajax call completes. That way, you can use an async request.
function loadView(viewName, destination, callback){
var URL = "/popup/"+viewName;
var client = new XMLHttpRequest();
client.open('GET', URL);
client.onreadystatechange = function() {
if (client.readyState < 4) return; // Wait until the request completes
document.getElementById(destination).innerHTML = client.responseText;
callback();
}
client.send();
}
// Example of a call
loadView('contact.html', 'widgetBox', function() {
// Do whatever comes next
});

Related

jQuery append to vanilla javascript issue when injecting a facebook pixel in the dom

I have written a script which I have in the head section on my landing pages. What it does is that it loads a facebook pixel which I have stored in another part of my application which I access by calling an endpoint. This because I need to dynamically change the script without interfering with the code on the landing page itself. This code is written in Jquery but now I need jQuery gone from my application so I've tried to rewrite it using only vanilla javascript.
The problem is that it works just fine with the jQuery code, but when I've tried to replace it with vanilla Javascript it does not seem to inject the code in the correct way. The output in the DOM looks exactly the same but it does not fire the pixel somehow.
So my question is. Why is this?
Here is the working example of my jQuery script
<script>
$.get('https://api.mydomain.com/script', function (data) {
$('head').append(data);
});
</script>
Here is my vanilla Javascript version
<script>
var theUrl = 'https://api.mydomain.com/script';
let xhr = new XMLHttpRequest();
xhr.open("GET", theUrl);
xhr.send();
xhr.onload = function() {
document.querySelector("head").insertAdjacentHTML("beforeend", xhr.response);
};
</script>
I think the issue is with insertAdjacentHTML - just a guess, but maybe it only works for HTML (divs, images, etc.) rather than scripts. Hopefully this workaround is an acceptable solution:
(function() {
const
exampleScript = getScriptContent(`
<script>
alert("example script loaded");
<\/script>
`),
s = document.createElement("script"),
t = document.createTextNode(exampleScript);
s.appendChild(t);
document.getElementsByTagName("head")[0].appendChild(s);
function getScriptContent(htmlStr) {
const tempDiv = document.createElement("div");
tempDiv.innerHTML = htmlStr;
return tempDiv.innerText;
}
})();

Javascript read and display content of a file

I want to read a file that's saved in the same folder. Then I want to show its content in a div in index.html. The problem: when I used require("fs") it didn't work since it wasn't running server-side. I have been looking around and can't find a simple answer. I want to make my website a little dynamic, so here is the code that should fire upon a button click:
function videos() {
var body = *read a file("insertfilename")*;
console.log(body);
document.getElementById("body").innerHTML = body;
}
"body" in this case is just the id I gave the div.
!EDIT!
Now to explain it further. I want to use it as my main website. When I go onto there it should open an empty html file, which has a scriptfile as source. "onload" it should read a file , which is also already on the server, and put its content into a div inside of the body. If I click on a hotlink or a Button, it should read another file and put that content into that div instead. Maybe that gives a little clarification on what I am trying to do. I dont want to reload to open other sites of mine.
Seems like you need some basic file fetching since you are not using a server. Have you tried FileReader for javascript? It is a very simple and straightforward object. The example on the page seems similar to what you are trying to accomplish, except you want to fetch the file, not the user.
You can use AJAX. It stands for Asynchronous JavaScript And XML. You can send asynchronous requests to server with it. Just make sure that file that you are requesting is on the same domain as JS file.
function videos() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() { //this will execute when you receive response from the server
if (this.readyState == 4 && this.status == 200) {
document.getElementById("body").innerHTML = this.responseText;
console.log(this.responseText)
}
};
xhttp.open("GET", "filename.txt", true);
xhttp.send();
}
Here is W3schools tutorial if you want to learn more.

Request plain text file in javascript from URL?

I started a blog recently and coded it by hand. It is a static, CSS/HTML5 website. Upon sharing it with friends, I realized that when I would update it via FTP, it would be cached already by their browsers. I decided that I would keep all of my blog posts on new pages and then create a landing page that would somehow determine the newest post and forward users there after they clicked an enter button or something like that.
I was able to create a button that could forward them to a specific link, but I want to create a script that will always forward them to the newest page. So I created a file called 'getLatest.json' and uploaded it to an 'api' subfolder of my site. I then tried to use an XMLHttpRequest to load it:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
window.location = "http://latestBlogPost.com" +
xhttp.responseText.today;
//Today is a parent in the object returned.
}
};
xhttp.open("POST", "http://myWebsite.com/api/getLatest.json", true);
xhttp.send();
}
But that didn't work. The response was a null string. I tried using jquery to no avail.
I tried uploading a file called getLatest.html which contained the url in plaintext. That didn't work either.
tl;dr: Is there some way that I can get plaintext from a URL's html content?
edit: getLatest.json and getLatest.html contain a link to the newest blog post.
There are couple of ways to do this.
First your code is not working because you are using a "POST" it should be "GET", if you do that it will work.
Second easiest way is to create a java script file with variable declared and reference that file to your website
<script type="text/javascript" src="http://your javascript file"> </script>
This file contains your variable like this
var latestBlog = "http://....";
in your code use this variable. No more code required. but as i mentioned earlier if you change your HTTP Verb to get your code will work

Using JavaScript (only - no libraries) to load another page into div

What is the JavaScript equivalent of $('content').load('page.html'); I am trying to load content in another page into my div but I cannot find a method for plain old JavaScript.
The good old JavaScript:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
var myRequest = new XMLHttpRequest(); //XMLHttpRequest is how you do it
myRequest.onreadystatechange = function(e){
if(myRequest.readyState == 4 && myRequest.status == 200){
var data = myRequest.responseText; //returned data
document.querySelector("div").innerHTML = data; //not safe but whatever
}
};
myRequest.open("get", "url here", true);
myRequest.send();
It is always better to do it with plain JavaScript first before using those fancy jQuery one-method-takes-care-of-everything-for-you methods.
Your question has two parts:
Grabbing some content on a server from the client
Pushing that content into a div.
For part one, see this thread for instructions on using XMLHTTPRequest():
HTTP GET request in JavaScript?
For part two, as for populating the div, it's this simple:
document.getElementById('content').innerHTML = 'someContent';
Note that you may want to scrub your content before populating the div depending on the source of the page you are requesting, as using JS to populate a div with raw HTML is an attack vector that hackers might try to exploit.
Have you tried taking a look at using iframes? http://www.w3schools.com/tags/tag_iframe.asp
It's called an XML HTTP Request (XHR). See the docs here.
As you can see from the source code here, jQuery's load() function calls the ajax() function to load the external html.
Under the hood, the ajax() function uses XMLHttpRequest which is how you would retrieve the file using vanilla JavaScript.

How to load local JSON files in Javascript

I'm writing a web app (well, actually it will eventually be an OS X Dashboard widget, but I decided to prototype it first as a simple web page) that needs to load some initializing data from a local JSON file. My code looks like this:
function loadDatos() {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'datos.json', true);
xobj.onReadyStateChange = function () {
if (xobj.readyState == 4) {
var jsonTexto = xobj.responseText;
ProcessTheData(jsonTexto);
}
}
xobj.send(null);
}
The function get called from an onLoad() event in the HTML file's BODY tag. Now, from what I see when debugging, the function gets executed, but the onReadytStateChange event handler never gets called.
What should I do? I thought it was a bit odd to use a XMLHttpRequest to access a local file, but the new tutorials I've seen that deal with this issue seem to say that it should work (the 99% of docs I've seen talk about how to load JSON from a remote server, not from a local file).
I'm testing using Firefox 3.6.10, but I've also tried with Safari 4.
onreadystatechange property has no capital letters. See: MDC XMLHttpRequest
Unless we add extension .json and MIMETYPE application\json, IIS will throw an error.
See here: http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/cd72c0dc-c5b8-42e4-96c2-b3c656f99ead.mspx?mfr=true

Categories

Resources