diff --git a/src/core/PageSpeedService.js b/src/core/PageSpeedService.js new file mode 100644 index 0000000..f15441b --- /dev/null +++ b/src/core/PageSpeedService.js @@ -0,0 +1,47 @@ +/** + * @file Functions for interacting with the Google PageSpeed Insights API. + */ + +/** + * Proxy URL that will make the actual Page Speed request and return data. + * The requests are made securely from a serverless function, to keep the API key private. + */ +const PAGE_SPEED_API_URL = "https://carbon-calculator-proxy.netlify.app/.netlify/functions/page-speed"; + +/** + * Make Google PageSpeed Insights API request and return data. + * + * @param {string} urlToMeasure - URL to measure the performance of. + * @param {bool} logDebug - Whether to log results of request to the console for debugging. + * @returns {Promise|Promise} @see https://developers.google.com/speed/docs/insights/v5/reference/pagespeedapi/runpagespeed#response + */ +export const makePageSpeedAPIRequest = async (urlToMeasure, logDebug = false) => { + // Proxy URL using serverless function that will return data. + const proxyRequestUrl = `${PAGE_SPEED_API_URL}?url=${encodeURIComponent(urlToMeasure)}`; + + // Debug: log intro to console. + if (logDebug) { + console.log(`~~~~~~ DEBUG: Google PageSpeed Results`); + console.log(`URL to be measured: "${urlToMeasure}"`); + console.log(`Making request to: "${proxyRequestUrl}"`); + } + + // Make request. + try { + const response = await fetch(proxyRequestUrl); + if (!response.ok) { + throw new Error(`Fetch error encountered. Response status: ${response.status}`); + } + + const result = await response.json(); + + // Debug: log results to console. + if (logDebug) { + console.log(`Results JSON response:`, result); + } + return result; + } catch (error) { + console.error("Error with Page Speed API request:", error.message); + return null; + } +}; diff --git a/src/panels/welcome/welcome.html b/src/panels/welcome/welcome.html index 8b8af27..4712fb6 100644 --- a/src/panels/welcome/welcome.html +++ b/src/panels/welcome/welcome.html @@ -36,8 +36,9 @@

Welcome to Carbon Visualizer

+

diff --git a/src/panels/welcome/welcome.js b/src/panels/welcome/welcome.js index 7c1e301..0ca4d25 100644 --- a/src/panels/welcome/welcome.js +++ b/src/panels/welcome/welcome.js @@ -1,5 +1,6 @@ // Welcome panel JavaScript import { extensionManager } from "../../core/ExtensionManager.js"; +import { makePageSpeedAPIRequest } from "../../core/PageSpeedService.js"; export function initializePanel(panelType, data) { // Get the container element @@ -9,16 +10,43 @@ export function initializePanel(panelType, data) { return; } - // Get analyze button from within the container + // Get analyze button from within the container. const analyzeBtn = container.querySelector('#analyze-page-btn'); + const analyzeErrorMessage = container.querySelector('#analyze-page-error'); - // Check if button exists before adding event listener + // Check if button exists before doing more with it. if (!analyzeBtn) { return; } + + // Store original/default button text. + const analyzeBtnText = analyzeBtn.textContent; // Event listener for analyze button analyzeBtn.addEventListener('click', async () => { - await extensionManager.openPanel('results'); + // For now, just show a simple message within the button. + analyzeBtn.disabled = true; + analyzeBtn.textContent = 'Analyzing page...'; + if (analyzeErrorMessage) { + analyzeErrorMessage.textContent = ''; + } + + // Make API request. + const currentPageURL = window.location.toString(); + const pageSpeedResults = await makePageSpeedAPIRequest(currentPageURL, true); + + // Display error message in UI if there was an error or nothing was returned. + if (!pageSpeedResults || Object.keys(pageSpeedResults).length === 0) { + if (analyzeErrorMessage) { + analyzeErrorMessage.textContent = 'Sorry! An error occurred when making the API request that tests the page. Please try again a little later. If this continues to happen, please let us know!'; + } + + // Reset button back to usable state. + analyzeBtn.textContent = analyzeBtnText; + analyzeBtn.disabled = false; + } else { + // Success. Open results panel. + await extensionManager.openPanel('results'); + } }); }