Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/core/PageSpeedService.js
Original file line number Diff line number Diff line change
@@ -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<JSON>|Promise<null>} @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;
}
};
3 changes: 2 additions & 1 deletion src/panels/welcome/welcome.html
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ <h2 class="cv-panel--welcome__title">Welcome to Carbon Visualizer</h2>
</ul>

<button class="cv-btn cv-btn--primary" id="analyze-page-btn">
Analyze this website
Analyze this page
</button>
<p class="message message--negative" id="analyze-page-error"></p>
</div>
</main>
</div>
Expand Down
34 changes: 31 additions & 3 deletions src/panels/welcome/welcome.js
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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');
}
});
}