how to connect pagespeed API to Google sheet? - javascript

I am trying to get create a dashboard on google data studio from the pageSpeed API.
I want to get data on google sheet schedule everyday and after it will update data on google data studio.
I found some codes on official documentation.
It needs some connection with google sheet.
Please fix the below code as per google sheet for website.com.
<script>
function run() {
const url = setUpQuery();
fetch(url)
.then(response => response.json())
.then(json => {
// See https://developers.google.com/speed/docs/insights/v5/reference/pagespeedapi/runpagespeed#response
// to learn more about each of the properties in the response object.
showInitialContent(json.id);
const cruxMetrics = {
"First Contentful Paint": json.loadingExperience.metrics.FIRST_CONTENTFUL_PAINT_MS.category,
"First Input Delay": json.loadingExperience.metrics.FIRST_INPUT_DELAY_MS.category
};
showCruxContent(cruxMetrics);
const lighthouse = json.lighthouseResult;
const lighthouseMetrics = {
'First Contentful Paint': lighthouse.audits['first-contentful-paint'].displayValue,
'Speed Index': lighthouse.audits['speed-index'].displayValue,
'Time To Interactive': lighthouse.audits['interactive'].displayValue,
'First Meaningful Paint': lighthouse.audits['first-meaningful-paint'].displayValue,
'First CPU Idle': lighthouse.audits['first-cpu-idle'].displayValue,
'Estimated Input Latency': lighthouse.audits['estimated-input-latency'].displayValue
};
showLighthouseContent(lighthouseMetrics);
});
}
function setUpQuery() {
const api = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed';
const parameters = {
url: encodeURIComponent('website.com')
};
let query = `${api}?`;
for (key in parameters) {
query += `${key}=${parameters[key]}`;
}
return query;
}
function showInitialContent(id) {
document.body.innerHTML = '';
const title = document.createElement('h1');
title.textContent = 'PageSpeed Insights API Demo';
document.body.appendChild(title);
const page = document.createElement('p');
page.textContent = `Page tested: ${id}`;
document.body.appendChild(page);
}
function showCruxContent(cruxMetrics) {
const cruxHeader = document.createElement('h2');
cruxHeader.textContent = "Chrome User Experience Report Results";
document.body.appendChild(cruxHeader);
for (key in cruxMetrics) {
const p = document.createElement('p');
p.textContent = `${key}: ${cruxMetrics[key]}`;
document.body.appendChild(p);
}
}
function showLighthouseContent(lighthouseMetrics) {
const lighthouseHeader = document.createElement('h2');
lighthouseHeader.textContent = "Lighthouse Results";
document.body.appendChild(lighthouseHeader);
for (key in lighthouseMetrics) {
const p = document.createElement('p');
p.textContent = `${key}: ${lighthouseMetrics[key]}`;
document.body.appendChild(p);
}
}
run();
</script>
some similar codes but i cant find the source of the codes
youtube video link

Related

retrieving and rendering messages from sessionStorage from a form

In a course I'm taking my lecturer wrote the below code for submitting data from a form when the submit button is pressed. It stores this to sessionStorage and then renders the received messages below the form. I made sure to copy it exactly and mine doesn't work. It seems to be because the .fullName, .email, .feedbackType and .comment are not being assigned a type. When I ran the lecturers code file from my vscode and checked it in the browser his worked fine. My work is identical to his bar some different CSS styles. It is currently just putting undefined for each item
function submitMessage(event) {
event.preventDefault();
const email = document.getElementById('email').value;
const fullName = document.getElementById('fullName').value;
const feedbackType = document.getElementById('feedbackType').value;
const comment = document.getElementById('comment').value;
const messageObject = {
email,
fullName,
feedbackType,
comment,
};
let currentMessages = [];
if (window.sessionStorage.getItem('messages')) {
currentMessages = JSON.parse(
window.sessionStorage.getItem('messages')
);
}
currentMessages.push({
messageObject
});
/*temporary fix, find a solution for this error, .push not working/recognised. Code matching lectures is currentMessages.push(messageObject)*/
window.sessionStorage.setItem(
'messages',
JSON.stringify(currentMessages)
);
renderMessages();
}
function renderMessages() {
let currentMessages = [];
if (window.sessionStorage.getItem("messages")) {
currentMessages =
JSON.parse(
window.sessionStorage.getItem("messages")
);
}
let listItems = [];
for (let i = 0; i < currentMessages.length; i++) {
let listItem = " ";
const currentMessage = currentMessages[i];
listItem += `<dt>${currentMessage.fullName} - ${currentMessage.email}</dt>`;
listItem += `<dd>${currentMessage.feedbackType}: ${currentMessage.comment}</dd>`;
listItem += `<br />`;
listItems.push(listItem);
}
let descList = document.getElementById('currentMessages');
descList.innerHTML = listItems.join('');
}
renderMessages();

How to attach Media to a Facebook Post using the API

I have followed the Facebook documentation to request access token and post to a Facebook Page.
Now, I wish to create a post and attach some photos to that post but Facebook is only posting the text body and not including the photo files.
Here is how I did it:
...
let mediaIds = [];
for (let photoUrl of photoUrls) {
let mediaUploadUrl = `https://graph.facebook.com/${pageId}/photos?url=${photoUrl}&access_token=${pageAccessToken}`;
let response = await axios.post(mediaUploadUrl);
let { id } = response.data;
if (id) {
mediaIds.push(id);
}
}
// Now that we have the mediaIds, let's attach them to the post as below:
let urlParams = new URLSearchParams();
urlParams.append("access_token", pageAccessToken);
urlParams.append("message", "Hello World");
let postUrl = `https://graph.facebook.com/${pageId}/feed`;
if (mediaIds.length > 0) {
for (let i = 0; i < mediaIds.length; i++) {
let mediaId = mediaIds[i];
let mediaIdObject = { media_fbid: mediaId };
urlParams.append(`attached_media[${i}]`, mediaIdObject);
}
}
try {
let { data } = await axios.post(postUrl, urlParams);
let postId = data.id;
} catch (e) {
done = false;
console.log(e); //An unknown error has occurred is the error message I keep getting
}
...
All I keep getting in return is
An unknown error has occurred
But if I go to the Facebook Page, I noticed the text body was posted but not the photo attachments.
Any ideas on fixing this would be really appreciated.
Appending an object to urlParams, as you do in
let mediaIdObject = { media_fbid: mediaId };
urlParams.append(`attached_media[${i}]`, mediaIdObject);
produces a URL parameter like
attached_media[0]=[object Object]
Use
urlParams.append(`attached_media[${i}]`, JSON.stringify(mediaIdObject));
instead.

Book Search dynamic web application

This web program name is Book search by using html, css, and javascript. In this code how can i do http GET request to searchInput element and how can i put bootstrap spinner to html searchInput element. Please explain and help me. According to this code two steps are not getting, the two steps are
When a value is entered in the HTML input element with id searchInput, x books option is selected in the HTML select element with id selectDisplayCount, an HTTP GET request with a valid url parameters title and maxResults should be made
When a value is entered in the HTML input element with id searchInput, x books option is selected in the HTML select element with id selectDisplayCount, an HTTP GET request should be made to fetch and display x book items
let searchInputEl = document.getElementById("searchInput");
let spinnerEl = document.getElementById("spinner");
let searchresultsEl = document.getElementById("searchResults");
let selectDisplayCountEl = document.getElementById("selectDisplayCount");
let bookcount = selectDisplayCountEl.value;
let formData = {
count: "10 Books",
};
function createAndAppendSearchResult(result) {
let {
title,
imageLink,
author
} = result;
let resultItemEl = document.createElement("div");
resultItemEl.classList.add("country-card", "col-6", "mr-auto", "ml-auto", "d-flex", "flex-column");
searchresultsEl.appendChild(resultItemEl);
let imageEl = document.createElement("img");
imageEl.classList.add("image", "mt-auto", "mb-auto");
imageEl.src = imageLink;
resultItemEl.appendChild(imageEl);
let authorEl = document.createElement("p");
authorEl.classList.add("author-name");
authorEl.textContent = author;
resultItemEl.appendChild(authorEl);
}
function displaySearchResults(searchresult) {
for (let result of searchresult) {
let titleName = result.title;
if (titleName.includes(searchInputEl.value)) {
createAndAppendSearchResult(result);
} else {
searchInputEl.textontent = "No reuslts found";
}
}
}
function searchBook(event) {
if (event.key === "Enter") {
let url = "https://apis.ccbp.in/book-store?title=kalam&maxResults=30" + bookcount;
let options = {
method: "GET"
};
spinnerEl.classList.remove("d-none");
searchresultsEl.classList.add("d-none");
fetch(url, options)
.then(function(response) {
return response.json();
})
.then(function(jsonData) {
searchresultsEl.classList.remove("d-none");
spinnerEl.classList.add("d-none");
console.log(jsonData)
let {
search_results
} = jsonData;
console.log(JSON.stringify(jsonData))
displaySearchResults(jsonData.search_results);
});
}
}
selectDisplayCountEl.addEventListener("change", function(event) {
formData.count = event.target.value;
console.log(formData.count);
});
searchInputEl.addEventListener("keydown", searchBook);
When the HTTP GET request is successful, then the searchResults element should consist of HTML image elements with src attribute value as the value of key 'imageLink' and HTML paragraph elements with text content as the value of key 'author' from HTTP response

I'm just starting with JS and I don't really understand how setTimeout works

I am developing a trivia page with a series of questions that I get through an API. When I give to start the game on the main page, I want to redirect me to a second page where the available categories will appear and when I click on them, the questions will appear with multiple answers.
Luckily I have managed to do all this, however, when I switch from one page to another I have not been able to get the categories to appear. They only appear if I am already on that page and I create a button to call the function that displays them.
I had thought of doing this function in this way so that it would switch me to the other page and then load the questions but I have not been able to get it to work.
Does anyone have a solution or know why it is not working?
function get_dataJson() {
let data_json = [];
fetch('https://opentdb.com/api.php?amount=10')
.then(response => response.json())
.then(data => data.results.forEach(element => {
data_json.push(element);
}));
return data_json;
}
let trivial_data = get_dataJson();
function startGame() {
let div_username = document.createElement("div");
let name = document.createElement("h2");
name.innerHTML = document.getElementById("name").value;
div_username.appendChild(name);
let categories = get_categories(trivial_data);
setTimeout("location.href='./game.html'", 1000);
setTimeout(function(){
document.getElementById('nav-game').appendChild(div_username);
show_categories(categories);
},2000);
}
function get_categories(trivial_data) {
let categories = [];
trivial_data.forEach(element => {
categories.push(element.category)
});
console.log(categories);
return categories;
}
function show_categories (categories) {
let div_categories = document.createElement("div");
let count = 0;
categories.forEach ( element => {
let element_category = document.createElement("button");
element_category.innerHTML = element;
element_category.id = count;
element_category.onclick = function() {
get_question(element_category.id);
};
count++;
div_categories.appendChild(element_category);
});
div_categories.className = 'categories';
document.getElementById("categories").appendChild(div_categories);
}
function get_question (pos) {
document.getElementById("categories").style.displays = 'none';
let question = document.createElement("h2");
question.innerHTML = trivial_data[pos].question;
let correct_answer = trivial_data[pos].correct_answer;
let incorrect_answers = trivial_data[pos].incorrect_answers;
let options = incorrect_answers.concat(correct_answer);
options = options.sort();
let div_choices = document.createElement("div");
options.forEach(element => {
let choice = document.createElement('button');
choice.innerHTML = element;
choice.id = 'true' ? element == correct_answer : 'false';
div_choices.appendChild(choice);
});
div_choices.className = 'answers';
document.getElementById("questions").appendChild(question);
document.getElementById("questions").appendChild(div_choices);
}
The first thing you should do is make sure you understand how to use fetch to get data asynchronously
async function get_dataJson() {
const response = await fetch('https://opentdb.com/api.php?amount=10');
const json = await response.json();
return json.results;
}
(async function(){
const trivial_data = await get_dataJson();
console.log(trivial_data);
})()
Then, rather than changing page, just stay on the same page and add/remove/hide elements as necessary - it looks like you have that bit sorted.

"weather is not defined" error when working with openwethermap API

I'm somewhat new to working with API's using vanilla JavaScript and I keep running into this error when trying to access the "description" within the "weather object". The console keeps reading "weather is not defined". I'm using the open weather map API. In theory I should be able to retrieve using data.current.weather.description. but that doesn't work, along with the other variations I've tried. Here is my current code.
window.addEventListener("load", () => {
let long;
let lat;
let temperatureDescription = document.querySelector(
".temperature-description"
);
let temperatureDegree = document.querySelector(".temperature-degree");
let locationTimezone = document.querySelector(".location-timezone");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
long = position.coords.longitude;
lat = position.coords.latitude;
const proxy = "https://cors-anywhere.herokuapp.com/";
const api = `${proxy}https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${long}&
exclude=hourly,daily&appid=da5463709c92ab1860d3a81037565c6e`;
fetch(api)
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
const {
temp,
weather: { description },
} = data.current;
//Set DOM Elements from the API
let kelvinToCelsius = temp - 273.15;
temperatureDegree.textContent = kelvinToCelsius.toFixed(0);
temperatureDescription.textContent = description;
locationTimezone.textContent = data.timezone;
});
});
} else {
}
});
If anyone has ran into this issue and solved, it would be much appreciated if you filled me in.

Categories

Resources