I have built a javascript code to be able to read any Youtube video transcript (gapi.client.youtube.captions.download). The auth 2.0 works fine, I run my app in a local web server everything is fine, the problem is that when I run the request I have the error 403: cb=gapi.loaded_0:164 GET https://content.googleapis.com/youtube/v3/captions/My_API_Key 403 I have not found any solution here in StackOverflow.. any idea ?
Here is my js file:
const CLIENT_ID = 'My_Client_ID';
const DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest"];
const SCOPES = 'https://www.googleapis.com/auth/youtube.readonly';
const authorizeButton = document.getElementById('enter-button');
const signoutButton = document.getElementById('exit-button');
const content = document.getElementById('content');
// default youtube channel
const defaultChannel = 'googledevelopers';
// Load auth2 library
function handleClientLoad(){
gapi.load('client:auth2', initClient);
}
// Init API client library and set up sing in listeners
function initClient(){
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(() => {
// Listen for sing state changes
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle initial sign in state
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignouClick;
});
}
// update UI sign in state changes
function updateSigninStatus(isSignedIn){
if(isSignedIn){
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
content.style.display = 'block';
getChannel(defaultChannel);
}else{
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
content.style.display = 'none';
}
}
// Handle Login
function handleAuthClick(){
gapi.auth2.getAuthInstance().signIn();
}
// Handle Logout
function handleSignouClick(){
gapi.auth2.getAuthInstance().signOut();
}
// Display channel Data
function showChannelData(data){
const channelData = document.getElementById('channel-data');
channelData.innerHTML = data;
}
// Get channel from API
function getChannel(channel){
gapi.client.youtube.captions.download({
id: 'guMGyC1tUYAdL3hgBlcGnW4Rt_bBUbtp'
})
.then(response => {
console.log(response);
const channel = response.result.items[0];
})
.catch(err => alert('No Channel By THat Name'));
}
And here is my index.ejs file:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Your awesome Youtube search engine</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Awesome videos!" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>
<header>
<h1 class="w100 text-center">YouTube Viral Search</h1>
</header>
<div class="container">
<p>Login with Google</p>
<button class="btn green" id="enter-button">Log In</button>
<button class="btn green" id="exit-button">Log Out</button>
<br />
<div id="content">
<div class="row">
<div id="channel-data" class="col s12"></div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
<script src="/javascripts/appYT.js"></script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
enter code here
You can use the following code for get the transcript in a given video.
This is the working jsfiddle
N.B here I have the videoId zenMEj0cAC4, but you can change it as you desire.
$.ajax({
type: "GET",
url: "https://video.google.com/timedtext?type=track&v=zenMEj0cAC4&id=0&lang=en",
crossDomain: true,
}).done(function(data) {
console.log(data);
getCaption(data);
});
var parser, xmlDoc;
var HTML_captions = "";
// Parse the AJAX response and get the captions.
function getCaption(ajax_response) {
try {
parser = new DOMParser();
xmlDoc = parser.parseFromString(ajax_response, "text/xml");
//console.log(ajax_response);
//console.log(xmlDoc.getElementsByTagName("transcript").length);
if (xmlDoc.getElementsByTagName("transcript").length > 0) {
// Loop the results of the xmlDoc:
for (var i = 0; i < xmlDoc.getElementsByTagName("transcript")[0].childNodes.length; i++) {
console.log(xmlDoc.getElementsByTagName("transcript")[0].childNodes[i].innerHTML);
HTML_captions += xmlDoc.getElementsByTagName("transcript")[0].childNodes[i].innerHTML + "<br/>";
}
} else {
// Loop the results of the ajax_response;
for (var i = 0; i < ajax_response.getElementsByTagName("transcript")[0].childNodes.length; i++) {
console.log(ajax_response.getElementsByTagName("transcript")[0].childNodes[i].innerHTML);
HTML_captions += ajax_response.getElementsByTagName("transcript")[0].childNodes[i].innerHTML + "<br/>";
}
}
document.getElementById("demo").innerHTML = "<i>Preparing captions...</i>";
setTimeout(fillData(), 2000);
} catch (err) {
console.log(err);
document.getElementById("demo").innerHTML = ('Error at getCaption function - see console form more details.');
alert('Error at getCaption function - see console form more details.');
}
}
// Fill the data "captions" in a HTML "div" control.
function fillData() {
try {
document.getElementById("demo").innerHTML = HTML_captions;
} catch (err) {
console.log(err);
document.getElementById("demo").innerHTML = ('Error at fillData function - see console form more details.');
alert('Error at fillData function - see console form more details.');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div id="demo"><i>Loading captions...</i></div>
Just in case you need more information about how you can get automatic closed captions, you can refer to these answers in Stack Overflow:
Get closed caption “cc” for Youtube video
Extract automatic captions from YouTube video
Related
I have this html code (below), which works perfectly as a hosted file (meaning the code is working) -
<!DOCTYPE html>
<html>
<head>
<title>Read Text File</title>
<!--<script src="https://thunkable.github.io/webviewer-extension/thunkableWebviewerExtension.js" type="text/javascript"></script>-->
<script>
var ThunkableWebviewerExtension = (function () {
const postMessageToWebview = (message) => {
if (window.ReactNativeWebView) {
window.ReactNativeWebView.postMessage(message);
} else {
window.parent.postMessage(message, '*');
}
};
const getReceiveMessageCallback = (fxn, hasReturnValue) => (event) => {
if (typeof fxn === 'function') {
if (event.data) {
let dataObject;
try {
dataObject = JSON.parse(event.data);
} catch (e) {
// message is not valid json
}
if (dataObject && dataObject.type === 'ThunkablePostMessage' && hasReturnValue) {
fxn(dataObject.message, (returnValue) => {
const returnMessageObject = { type: 'ThunkablePostMessageReturnValue', uuid: dataObject.uuid, returnValue };
postMessageToWebview(JSON.stringify(returnMessageObject));
});
} else if (!hasReturnValue && (!dataObject || dataObject.type !== 'ThunkablePostMessage')) {
fxn(event.data);
}
}
}
};
return {
postMessage: postMessageToWebview,
receiveMessage: function(fxn) {
const callbackFunction = getReceiveMessageCallback(fxn, false);
document.addEventListener('message', callbackFunction, false);
window.addEventListener('message', callbackFunction, false);
},
receiveMessageWithReturnValue: function(fxn) {
const callbackFunction = getReceiveMessageCallback(fxn, true);
document.addEventListener('message', callbackFunction, false);
window.addEventListener('message', callbackFunction, false);
},
};
})();
</script>
</head>
<body>
<input type="file" name="inputfile" id="inputfile">
<br>
<pre id="output"></pre>
<script type="text/javascript">
document.getElementById('inputfile')
.addEventListener('change', function() {
var fr=new FileReader();
fr.onload=function(){
//document.getElementById('output').textContent=fr.result;
var msg = fr.result;
ThunkableWebviewerExtension.postMessage(msg);
}
fr.readAsText(this.files[0]);
})
</script>
</body>
</html>
What I want to do is, turn this whole code into a long URL, and I found that by using 'data:text/html,<meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"/>' at the start, then adding the code.
So the HTML url would become something like - 'data:text/html,<meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"/><!DOCTYPE html><html><head> ...'
I can see the file upload button, and even can select and upload a file. But, the script parts are not working - I am unable to catch the error here 😪
Kindly guide/advice me here... Thanks!
After experimenting a little bit, I think the problem might be that you haven't url-encoded it. Try using this instead of just pasting in the whole thing directly
(or copy it from here)
data:text/html,%3C!DOCTYPE%20html%3E%0A%3Chtml%3E%0A%3Chead%3E%0A%20%20%20%20%3Ctitle%3ERead%20Text%20File%3C/title%3E%0A%20%20%20%20%3C!--%3Cscript%20src=%22https://thunkable.github.io/webviewer-extension/thunkableWebviewerExtension.js%22%20type=%22text/javascript%22%3E%3C/script%3E--%3E%0A%20%20%20%20%3Cscript%3E%0A%20%20%20%20var%20ThunkableWebviewerExtension%20=%20(function%20()%20%7B%0A%20%20%20%20%20%20const%20postMessageToWebview%20=%20(message)%20=%3E%20%7B%0A%20%20%20%20%20%20%20%20if%20(window.ReactNativeWebView)%20%7B%0A%20%20%20%20%20%20%20%20%20%20window.ReactNativeWebView.postMessage(message);%0A%20%20%20%20%20%20%20%20%7D%20else%20%7B%0A%20%20%20%20%20%20%20%20%20%20window.parent.postMessage(message,%20'*');%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%7D;%0A%20%20%20%20%0A%20%20%20%20%20%20const%20getReceiveMessageCallback%20=%20(fxn,%20hasReturnValue)%20=%3E%20(event)%20=%3E%20%7B%0A%20%20%20%20%20%20%20%20if%20(typeof%20fxn%20===%20'function')%20%7B%0A%20%20%20%20%20%20%20%20%20%20if%20(event.data)%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20let%20dataObject;%0A%20%20%20%20%20%20%20%20%20%20%20%20try%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20dataObject%20=%20JSON.parse(event.data);%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%20catch%20(e)%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20//%20message%20is%20not%20valid%20json%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%20%20%20%20if%20(dataObject%20&&%20dataObject.type%20===%20'ThunkablePostMessage'%20&&%20hasReturnValue)%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20fxn(dataObject.message,%20(returnValue)%20=%3E%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20const%20returnMessageObject%20=%20%7B%20type:%20'ThunkablePostMessageReturnValue',%20uuid:%20dataObject.uuid,%20returnValue%20%7D;%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20postMessageToWebview(JSON.stringify(returnMessageObject));%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7D);%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%20else%20if%20(!hasReturnValue%20&&%20(!dataObject%20%7C%7C%20dataObject.type%20!==%20'ThunkablePostMessage'))%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20fxn(event.data);%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%7D;%0A%20%20%20%20%0A%20%20%20%20%20%20return%20%7B%0A%20%20%20%20%20%20%20%20postMessage:%20postMessageToWebview,%0A%20%20%20%20%20%20%20%20receiveMessage:%20function(fxn)%20%7B%0A%20%20%20%20%20%20%20%20%20%20const%20callbackFunction%20=%20getReceiveMessageCallback(fxn,%20false);%0A%20%20%20%20%20%20%20%20%20%20document.addEventListener('message',%20callbackFunction,%20false);%0A%20%20%20%20%20%20%20%20%20%20window.addEventListener('message',%20callbackFunction,%20false);%0A%20%20%20%20%20%20%20%20%7D,%0A%20%20%20%20%20%20%20%20receiveMessageWithReturnValue:%20function(fxn)%20%7B%0A%20%20%20%20%20%20%20%20%20%20const%20callbackFunction%20=%20getReceiveMessageCallback(fxn,%20true);%0A%20%20%20%20%20%20%20%20%20%20document.addEventListener('message',%20callbackFunction,%20false);%0A%20%20%20%20%20%20%20%20%20%20window.addEventListener('message',%20callbackFunction,%20false);%0A%20%20%20%20%20%20%20%20%7D,%0A%20%20%20%20%20%20%7D;%0A%20%20%20%20%7D)();%0A%20%20%20%20%3C/script%3E%0A%3C/head%3E%0A%0A%3Cbody%3E%0A%20%20%20%20%3Cinput%20type=%22file%22%20name=%22inputfile%22%20id=%22inputfile%22%3E%0A%20%20%20%20%3Cbr%3E%0A%0A%20%20%20%20%3Cpre%20id=%22output%22%3E%3C/pre%3E%0A%20%20%20%20%0A%20%20%20%20%3Cscript%20type=%22text/javascript%22%3E%0A%20%20%20%20%20%20%20%20document.getElementById('inputfile')%0A%20%20%20%20%20%20%20%20%20%20%20%20.addEventListener('change',%20function()%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20%20%20%20%20%20%20%20var%20fr=new%20FileReader();%0A%20%20%20%20%20%20%20%20%20%20%20%20fr.onload=function()%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20//document.getElementById('output').textContent=fr.result;%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20var%20msg%20=%20fr.result;%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20ThunkableWebviewerExtension.postMessage(msg);%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%20%20%20%20fr.readAsText(this.files%5B0%5D);%0A%20%20%20%20%20%20%20%20%7D)%0A%20%20%20%20%3C/script%3E%0A%3C/body%3E%0A%3C/html%3E%0A
But I could be wrong -- I'm not very experienced with javascript
Json fetching has worked before in site for example here where i used the same processes - https://n-ce.github.io/Sea-arch
Here's the script
//FETCH
function content(a){
fetch(a+'.json').then(function (response) {
return response.json();
}).then(function (data) {
appendData(data);
}).catch(function (err) {
console.log('error: ' + err);
});
}
//Loading the objects
var root = document.getElementById('root');
function appendData(data) {
for (var i = 0; i < data.length; i++) {
var p = document.createElement("p");
p.innerHTML = data[i].Name;
root.appendChild(p);
}
}
// Remove Function
function remove(){
while (root.hasChildNodes()) {
root.removeChild(root.firstChild);
}
}
// Click decision making
var count = couns = 0;
function Sites() {
if(count%2==0){
content('Sites');
count++;
}
else{
count--;
remove();
}
}
function Animals() {
if (couns % 2 == 0) {
content('Animals');
couns++;
}
else {
couns--;
remove();
}
}
And this is the HTML
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JSON SD</title>
<link rel="stylesheet" href="style.css"/>
</head>
<body onload="content('Onload')">
<span>
<button onclick="Animals()">Load Animals</button>
<button onclick="Sites()">Load Sites</button>
</span>
<div id="root"></div>
<script src="script.js"></script>
</body>
</html>
There is no way for me to debug this given that the console doesnot throw any errors since its working fine in localhost.
Im fairly new to the Fetch API But
Im thinking maybe it is because the json files are being transferred are taking too long?
Can someone please highlight whats the issue?
Here's how it worked for github pages, thanks to #programmarRaj for highlighting
Script
//FETCH
function content(a){
fetch("./"+a+".json").then(function (response) {
return response.json();
}).then(function (data) {
appendData(data);
}).catch(function (err) {
console.log('error: ' + err);
});
}
So I'm trying to experiment with accessing my google spreadsheet using JS, and I'm a beginner, and probably way in over my head, but I need help
So I have this script
<!DOCTYPE html>
<html>
<head>
<title>Google Sheets API Quickstart</title>
<meta charset="utf-8" />
</head>
<body>
<p>Google Sheets API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" style="display: none;">Authorize</button>
<button id="signout_button" style="display: none;">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = 'CLIENT_ID';
var API_KEY = 'API_KEY';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://sheets.googleapis.com/$discovery/rest?version=v4"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/spreadsheets.readonly";
var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listMajors();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
function listMajors() {
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: 'ID',
range: 'Class Data!A1:A1',
}).then(function(response) {
var range = response.result;
console.log(range);
if (range.values.length > 0) {
appendPre('Name, Major:');
for (i = 0; i < range.values.length; i++) {
var row = range.values[i];
// Print columns A and E, which correspond to indices 0 and 4.
appendPre(row[0] + ', ' + row[4]);
}
} else {
appendPre('No data found.');
}
}, function(response) {
appendPre('Error: ' + response.result.error.message);
});
}
listMajors()
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
Basically what I'm trying to do here is to access my spreadsheet and print the first column of the first row as a range of (A1 to A1), and my function listMajors() is supposed to do it, but I'm struck with this error
"<a class='gotoLine' href='#144:9'>144:9</a> Uncaught ReferenceError: gapi is not defined"
You are calling listMajors before the script tag with src="https://apis.google.com/js/api.js" is actually loaded. The reason for that is that gapi is being set up asynchronously.
In this case, listMajors() at the end of the script tag is being executed before gapi is even loaded. You are already calling it in the updateSigninStatus so I'm guessing that it will be properly called if you remove that line.
Note that I haven't looked into the code in that function (and you should probably make another question if that doesn't work and you can't figure why).
gapi needs to be loaded and you need to be authenticated, before your code can work. So the earliest place in your code, where you could call listMajors() would be in handleAuthClick():
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn().then(function() {
listMajors();
}, function() {
appendPre('Error while authenticating');
});
}
Don't forget to remove the two(!) existing calls to listMajors() from your code.
My Problem
I have a login page that gives the user the option to "Login With Google".
When the user successfully logs in, I am storing their username and Google ID in the Session.
My problem is, on pages OTHER than the login page, I need to check to see if they are logged in. I am having problems getting this to work. If they are not logged in, I need to know that - putting in a simple global page variable for now would be suffice.
This code handles the login: ( the renderButton function is called immediately on page load )
var googleID; // global variable to hold ID
var token; // will hold token ( once I get this working )
// Render Google Sign-in button
function renderButton() {
gapi.signin2.render('gSignIn', {
'scope': 'profile email',
'width': 240,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': onSuccess,
'onfailure': onFailure
});
}
// Sign-in success callback
function onSuccess(googleUser) {
gapi.client.load('oauth2', 'v2', function () {
var request = gapi.client.oauth2.userinfo.get({
'userId': 'me'
});
request.execute(function (resp) {
// GET GOOGLE ID
googleId = resp.id;
});
});
}
// Sign-in failure callback
function onFailure(error) {
alert(error);
}
// Sign out the user
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
loggedIn = false;
});
// Change Link
document.querySelector("#loginNav").innerHTML = "Login";
auth2.disconnect();
}
So this all works great on the login page.
But on my other pages, for instance my index page, how to I check to see if they are logged in?
I am trying this code, but getting NOTHING - no error, no success.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Login</title>
</head>
<body>
<div id="loginStatus">Status</div>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="js/popper.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="https://apis.google.com/js/client:platform.js?onload=init" async defer></script>
<script>
var auth2; // Global
var loggedIn;
function init() {
var appStart = function () {
gapi.load('auth2', initSigninV2);
};
}
/**
* Initializes Signin v2 and sets up listeners.
*/
var initSigninV2 = function () {
auth2 = gapi.auth2.init({
client_id: 'MY-CLIENT--ID-HERE',
scope: 'profile'
});
if (auth2.isSignedIn.get() == true) {
alert("Loggin in!");
loggedIn = "LOGGED IN";
} else {
alert("Not Logged IN!!!");
loggedIn = "NOT LOGGED IN";
}
document.getElementById("loginStatus").innerHTML = loggedIn;
}
</script>
</body>
</html>
Can anyone help me get this working?
Thank you.
I found a solution that worked for me.
Once logged in the first time, I simply saved the user credentials in a local storage variable.
Then on subsequent pages, I check that variable.
It's not fool-proof, but for my basic needs it works.
//app.js
const SEARCH_VIEW = document.getElementById('search_view');
const RESULTS_VIEW = document.getElementById('results_view');
const FORECAST_VIEW = document.getElementById('forecast_view')
function loadCities(){
const cities = ["London", "Paris", "Madrid", "Lisbon","Ohrid"];
var options = null;
var dest = document.getElementById('dest');
//Looping the cities
cities.forEach(city => {
options += '<option>' + city +'</options>';
});
dest.innerHTML = options;
}
function gettingWeather(){
// 1. Open the Url
var dest = document.getElementById('dest').value;
var url = ('http://api.openweathermap.org/data/2.5/weather?q='+ dest + '&appid=exampleAppId');
console.log(url);
console.log(dest);
// 2. Fetch the URL
fetch(url)
.then(response => {
if(response.status !== 200){
console.error("API failed, Status Code " + response.status);
return;
}
console.log(response);
// 3.We make the response .json and open the data
response.json().then(data => {
console.log(data);
RESULTS_VIEW.style.visibility = 'visible';
// Temperature
document.getElementById('Temperature').textContent = data.main.temp;
//Wind
document.querySelector('.Wind').textContent = data.wind.speed * data.wind.deg;
//Description
document.querySelector('.Description').textContent = data.weather[0].description;
});
}).catch(err => {
console.error("Fetch error "+ err);
});
}
function forecast(){
const API_BASE = 'http://api.openweathermap.org/data/2.5/forecast?mode=json&';
const API_KEY = 'appid=exampleAppId&';
var dest = document.getElementById('dest').value;
var url = API_BASE + API_KEY + 'q=' + dest.value;
console.log(url);
console.log(dest.value);
// 2. Fetch the URL
fetch(url)
.then(response => {
if(response.status !== 200){
console.error("API failed, Status Code " + response.status);
return;
}
console.log(response);
// 3.We make the response .json and open the data
response.json().then(data => {
console.log(data);
RESULTS_VIEW.style.visibility = 'hidden';
FORECAST_VIEW.style.visibility= 'visible';
});
}).catch(err => {
console.error("Fetch error "+ err);
});
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>Weather App</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width ,initial-scale=1">
<link href="styles.css" type="text/css" rel="stylesheet">
</head>
<body onload="loadCities();">
<div class="container">
<div id = "results_view">
<div class="inputWrapper">
<h1> Weather App </h1>
<p>Choose a city.</p>
<select id="dest" onchange="gettingWeather();" width=150 style="width:150px" ></select><br>
<label>Temperature</label>
<label class="Temperature" id="Temperature"></label><br>
<label>Wind</label>
<label class="Wind" id="Wind"></label><br>
<label>Description</label>
<h1 class="Description" id="Description"></h1>
<button onclick="forecast();">Forecast</button>
</div><!-- InputWrapper -->
</div>
<div id="forecast_view">
<h1>ForeCast</h1>
</div>
</div> <!-- end container -->
<script src="app.js"></script>
</body>
</html>
My task is to choose random 5 European cities and show some attributes but when a button is clicked I need to show a forecast of that city. I attempt to use Lexical Scoping to and half of my application works the easy part where i show some attribute taken from the API, when i clicked the button forecast I have error with the response Error but the error is also the city i choose.If I use any city the, in the forecast is undefined. I am not sure why I have this error and i dont have any insides tried closure If you don't know any answer I would appreciate even an insight or reference of work similar done.
Thank you
The problem is that your variable "dest" already contains the value. So you have in "dest" the name of your city and you use dest.value which is undefined because dest is a string and has no property called value.
to fix your code just remove .value in the url:
const API_BASE = 'http://api.openweathermap.org/data/2.5/forecast?mode=json&';
const API_KEY = 'appid=6c345b20d0c8fac21a36761eb7d6cd38&';
var dest = document.getElementById('dest').value;
var url = API_BASE + API_KEY + 'q=' + dest; // only dest NOT dest.value
console.log(dest); // the city selected