The scenario for my frontend javascript application is as following:
GET via URL an html/javascript file
execute it
Current I am trying the following frontend approach:
const myElement = document.createElement('myElement');
myElement.setAttribute('src', 'https://.../file.html');
document.body.appendChild(myElement);
And file.html looks like:
<html>
<head>
<script language="Javascript">
function doSomething() { }
</script>
</head>
<body onload="doSomething()"></body>
</html>
But nothing is happening.
Am I wrong to expect that on document.body.appendChild() , the file will be downloaded and executed as if the URL was opened from the browser?
Related
In my Node project I am trying to pull in some data to an HTML file from a JS file. I came across a couple of examples re: how to do this. Here's my question: should the following work?
In my index.html file I have the following:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="../../../lib/user-interface/jobs-list.js"></script>
<script type="text/javascript" >
function load() {
const jobsData = JSON.parse(data);
console.log(jobsData);
}
}
</script>
</head>
<body onload="load()">
// ... other code
</body>
</html>
The jobs-list.js file I'm pulling in here looks like this:
const data = [
"Job 1",
"Job 2",
"Job 3"
];
module.exports = data;
In other words, should this be sufficient to get the contents of my array logging to the console when I run the HTML file? If not, what am I missing? I'm just trying to get a basic understanding of how to pull in data from an external JS file into an HTML file when both belong to the same project.
When I try this as is, I get this error in the console of my browser:
(index):20 Uncaught ReferenceError: data is not defined
I am trying to draw a diagram by using below codes.
It works well.
As you can see, I should put some text information in the div.
If there is a sample.txt which includes this information in local drive, can I load it into div section dynamically instead of putting it manually?
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Sample Diagram</title>
</head>
<body>
<div class="diagram">
Title: Diagram
<!-- Participant FIRST
Participant SECOND
Participant D
Participant F
Participant G //-->
E->F: 2
SECOND->FIRST: 1
FIRST->SECOND: 1
C-->SECOND: Request token
C->E: 2
SECOND->FIRST: Forward request
FIRST->>C: Send token
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/js-sequence-diagrams/1.0.4/sequence-diagram-min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
UPDATE
/test/index.html
/test/js/index.js
/test/js/sample.txt
/test/sample.txt
index.js
// js-sequence-diagrams by bramp <http://bramp.github.io/js-sequence-diagrams/>
$(".diagram").sequenceDiagram({theme: 'simple'});
$(function(){
$.get("sample.txt", function(data) {
$(".diagram").text(data);
});
});
sample.txt
Title: Diagram
SECOND->FIRST: 1
FIRST->SECOND: 1
C-->SECOND: Request token
C->E: 1
SECOND->FIRST: Forward request
FIRST->>C: Send token
Without inner text
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Sample Diagram</title>
</head>
<body>
<div class="diagram">
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js'></script>
<script src='http://cdnjs.cloudflare.com/ajax/libs/js-sequence-diagrams/1.0.4/sequence-diagram-min.js'></script>
<script src="js/index.js"></script>
</body>
</html>
Add a file-input element to the HTML page:
<input type="file" id="file" onchange="readTxT()"/>
And select sample.txt manually:
function readTxT(){
var reader = new FileReader();
var files=document.getElementById('file').files;
var f = files[0];
reader.onload = function(e) {
var text = reader.result;
$(".diagram").text(text).sequenceDiagram({theme: 'simple'});
}
reader.readAsText(f);
}
The simplest and easy way is to make get request to the server. And for that you have to use jQuery $.get function. Which will make a request for you.
Here is reference to jQuery.get()
USAGE
// make sure the PATH is correct for `sample.txt`
// $.get(your URL to the file, callback function)
$(function(){
$.get("sample.txt", function(data) {
$(".diagram").text(data);
});
});
If the sample.txt is available on the (http) server the site is hosted with (may be localhost), yes.
Assuming your directory structure is like this (/var/www/ is the server's root directory in my example):
/var/www/
index.html (The file without the diagram content)
sample.txt
js/
index.js
Place this in your index.js:
window.onload = function() {
$.get("sample.txt", function(data) {
$(".diagram").text(data).sequenceDiagram({theme: 'simple'});
});
}
If you're not using any HTTP server, you can't load files from the file system directly - that's part of the Javascript sandbox (security concept).
I would then recommend using something like in lx1412's answer, a manual file chooser is the only way how this could work then.
I've tested the script above using Firefox and an HTTP server; and my edit of lx1412's answer using Firefox without an HTTP server.
I get "ReferenceError: SpreadsheetApp is not defined" when i run the above code. Is there any error?
This is working in script editor but not working in separate file
<html>
<head>
<title>Site</title>
</head>
<body>
<p id="demo"></p>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script>
var ss = SpreadsheetApp.openById('1-wYHx2ynT1fMAUKHSeRDBABjE_cAbJ2tfBP_deKjhGs');
document.getElementById("demo").innerHTML =ss.getName();
</script>
</body>
</html>
Take a look at the Google Apps Script tutorials. For the most part, GAS is all server-side scripting, whereas you're trying to gain client-side access to a spreadsheet. It doesn't work like that. You'll need to follow one of the tutorials and open the script editor to begin writing your code.
You need to redirect call function in a way html apps script allows you. Please have a look at simple line below, which permits you to access any function
a file called "lookatme.html"
</script>
function doStuff() {
google.script.run.doStuff()
console.log("ggg")
}
</script>
if it is a .gs extension file unlike html file, it will recognize the code below and any extended apps scripts' built-in functions
a file called "anyfile.gs"
function doStuff() {
console.log("ggg")
// google.script.run.userClicked(userInfo)
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1i9of_RcoDih65x2h7-agSdCaUSvc1fvfOm4Y7dQEb-s/edit#gid=0")
var ws = ss.getSheetByName("Data")
ws.appendRow(["name"])
}
Here is my code:
<!DOCTYPE html>
<html lang="en" >
<head>
<script type="text/javascript">
function showResponse(response){
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
function onClientLoad(){
gapi.client.load('youtube','v3', onYouTubeApiLoad);
}
function onYouTubeApiLoad(){
gapi.client.setApiKey('MyActualKey');
search();
}
function search(){
var request = gapi.client.youtube.search.list({
part: 'snippet'
});
request.execute(onSearchResponse);
}
function onSearchResponse(response){
showResponse(response);
}
</script>
<title></title>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
</head>
<body>
<div id="response"></div>
</body>
</html>
This code is from Codecademy, and I thought I can use it on an html page and it would work.
I got an API key from google and I set my Youtube data api v3 setting to enabled in my google developers console, but this code gives me a blank page.
What am I doing wrong?
There are a few missing pieces, code snippets which codecademy likely took for granted but which are essential when placing it in your own server outside of their app. First of all, you need a line that actually loads the gapi library from google. You can put this in your code, just before the closing :
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
In short, this will get the library from Google's servers, and when it's loaded the library will automatically call your onClientLoad method, kicking off your app.
Next, you say you have an API key; make sure you put that key into your code by replacing this:
gapi.client.setApiKey('MyKey');
with this:
gapi.client.setApiKey('{WHATEVER_YOUR_ACTUAL_KEY IS');
Finally, as the commenters mentioned, your body is empty, so when your code executes the showResponse method there's no place to put what comes back. Add this:
<div id="response"></div>
I'm building a webpage and I want to re-use some HTML I have elsewhere on my website. The page I am building (index.html) can dynamically get and insert the HTML I want (existing.html) using XMLHttpRequest. However, the HTML I want to get is populated by some Javscript. That Javascript is not being executed when I load it into my new page:
index.html:
<html>
<head>
<script type = "text/javascript">
... //use XMLHttpRequest to load existing.html
initExistingHTML(); //this is function which populates loaded HTML, is not executed
</script>
</head>
<html>
existing.html:
<div>
<script type = "text/javascript">
function initExistingHTML() {
... // do some stuff
}
</script>
</div>
How can I load existing.html and run the script which populates it?
Once the page has loaded, add in existing.html via innerHTML. Rather than calling its functions, just let existing.html's code execute, which will do the same as if it were in the onload section.
EDIT: Or, you could just correct that typo you have. initExistingHTML != initExistingHtml.
lol