Skip to content

Commit

Permalink
Calculate the total size of the page.
Browse files Browse the repository at this point in the history
  • Loading branch information
idematos committed Dec 7, 2023
1 parent f018553 commit 02ecf04
Show file tree
Hide file tree
Showing 7 changed files with 154 additions and 156 deletions.
11 changes: 11 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,8 @@
"webpack": "^5.89.0",
"webpack-cli": "^4.10.0",
"webpack-merge": "^5.10.0"
},
"dependencies": {
"@tgwf/co2": "^0.13.9"
}
}
9 changes: 5 additions & 4 deletions public/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@
"256": "icons/icon-256.png",
"512": "icons/icon-512.png"
},
"background": {},
"background": {
"service_worker": "background.js"
},
"action": {
"default_title": "Ecoloader",
"default_popup": "popup.html"
},
"permissions": [
"storage"
],
"permissions": ["storage", "activeTab", "scripting", "webRequest"],
"host_permissions": ["<all_urls>"],
"content_scripts": [
{
"matches": [
Expand Down
18 changes: 8 additions & 10 deletions public/popup.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,15 @@
</head>
<body>
<div class="app">
<p class="counter-label">Counter</p>
<div id="counter" class="counter"></div>
<div class="button-container">
<button id="decrementBtn" class="button">-</button>
<button id="incrementBtn" class="button">+</button>
</div>
<!-- <p class="counter-label">Counter</p>-->
<!-- <div id="counter" class="counter"></div>-->
<!-- <div class="button-container">-->
<!-- <button id="decrementBtn" class="button">-</button>-->
<!-- <button id="incrementBtn" class="button">+</button>-->
<!-- </div>-->

<hr class="divider" />

<p class="title">Browser Extension is Ready!</p>
<p class="subtitle">Start by updating <code>popup.html</code></p>
<!-- <hr class="divider" />-->
<div id="totalSize">Calculating...</div>
</div>

<script type="application/javascript" src="popup.js"></script>
Expand Down
29 changes: 14 additions & 15 deletions src/background.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,18 @@
'use strict';

// With background scripts you can communicate with popup
// and contentScript files.
// For more information on background script,
// See https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Background_scripts
browser.webRequest.onCompleted.addListener(
function(details) {

browser.runtime.onMessage.addListener((request, sender) => {
if (request.type === 'GREETINGS') {
const message: string = `Hi ${
sender.tab ? 'Con' : 'Pop'
}, my name is Bac. I am from Background. It's great to hear from you.`;
const contentLengthHeader = details.responseHeaders?.find(header => header.name.toLowerCase() === 'content-length');

// Log message coming from the `request` parameter
console.log(request.payload.message);
// Send a response message
return Promise.resolve({ message });
}
});
const responseSize = contentLengthHeader?.value ? parseInt(contentLengthHeader.value, 10) : 0;
browser.storage.local.get({ totalSize: 0 }).then(function(result) {

const newTotalSize = parseInt(result.totalSize,10) + responseSize;

browser.storage.local.set({ totalSize: newTotalSize });
});
},
{ urls: ["<all_urls>"] },
["responseHeaders"]
);
46 changes: 11 additions & 35 deletions src/contentScript.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,20 @@
'use strict';

// Content script file will run in the context of web page.
// With content script you can manipulate the web pages using
// Document Object Model (DOM).
// You can also pass information to the parent extension.

// We execute this script by making an entry in manifest.json file
// under `content_scripts` property

// For more information on Content Scripts,
// See https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Anatomy_of_a_WebExtension#Content_scripts

// Log `title` of current active web page
const pageTitle: string =
document.head.getElementsByTagName('title')[0].innerHTML;
console.log(
`Page title is: '${pageTitle}' - evaluated by the extension's 'contentScript.js' file`
);

// Communicate with background file by sending a message
browser.runtime.sendMessage(
{
type: 'GREETINGS',
payload: {
message: 'Hello, my name is Con. I am from ContentScript.',
},
}
).then((response) => {
console.log(response.message);
});

// Listen for message
browser.runtime.onMessage.addListener((request, sender) => {
console.log({ request, sender })

if (request.type === 'COUNT') {
console.log(`Current count is ${request.payload.count}`);
}

// Send an empty response
// See: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage
return Promise.resolve();
});
// browser.runtime.onMessage.addListener((request, sender) => {
// console.log({ request, sender })
//
// if (request.type === 'COUNT') {
// console.log(`Current count is ${request.payload.count}`);
// }
//
// // Send an empty response
// // See: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/runtime/onMessage
// return Promise.resolve();
// });
194 changes: 102 additions & 92 deletions src/popup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,103 +3,113 @@
import './popup.css';

(function () {
// We will make use of Storage API to get and store `count` value
// More information on Storage API can we found at
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage
browser.storage.local.get({ totalSize: 0 }).then( (result) => {
const totalSize = result.totalSize;
document.getElementById("totalSize")!.innerText = totalSize/1000 + " KB";
});

// To get storage access, we have to mention it in `permissions` property of manifest.json file
// More information on Permissions can we found at
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions
const counterStorage = {
get: (cb: (count: number) => void) => {
browser.storage.sync.get(['count']).then((result) => {
cb(result.count);
});
},
set: (value: number, cb: () => void) => {
browser.storage.sync.set({
count: value,
}).then(cb);
},
};
function formatBytes(bytes: number, decimals = 2): string {
if (bytes === 0) return "0 Bytes";

function setupCounter(initialValue = 0) {
document.getElementById('counter')!.innerHTML = initialValue.toString();
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];

document.getElementById('incrementBtn')!.addEventListener('click', () => {
updateCounter({
type: 'INCREMENT',
});
});
const i = Math.floor(Math.log(bytes) / Math.log(k));

document.getElementById('decrementBtn')!.addEventListener('click', () => {
updateCounter({
type: 'DECREMENT',
});
});
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + " " + sizes[i];
}

function updateCounter({ type }: { type: string }) {
counterStorage.get((count: number) => {
let newCount: number;
// const counterStorage = {
// get: (cb: (count: number) => void) => {
// browser.storage.sync.get(['count']).then((result) => {
// cb(result.count);
// });
// },
// set: (value: number, cb: () => void) => {
// browser.storage.sync.set({
// count: value,
// }).then(cb);
// },
// };

if (type === 'INCREMENT') {
newCount = count + 1;
} else if (type === 'DECREMENT') {
newCount = count - 1;
} else {
newCount = count;
}

counterStorage.set(newCount, () => {
document.getElementById('counter')!.innerHTML = newCount.toString();

// Communicate with content script of
// active tab by sending a message
browser.tabs.query({ active: true, currentWindow: true }).then((tabs) => {
const tab = tabs[0];

browser.tabs.sendMessage(
tab.id!,
{
type: 'COUNT',
payload: {
count: newCount,
},
}).then((response) => {
console.log('Current count value passed to contentScript file');
}
).catch(console.error);
});
});
});
}

function restoreCounter() {
// Restore count value
counterStorage.get((count: number) => {
if (typeof count === 'undefined') {
// Set counter value as 0
counterStorage.set(0, () => {
setupCounter(0);
});
} else {
setupCounter(count);
}
});
}

document.addEventListener('DOMContentLoaded', restoreCounter);

// Communicate with background file by sending a message
browser.runtime.sendMessage(
{
type: 'GREETINGS',
payload: {
message: 'Hello, my name is Pop. I am from Popup.',
},
}).then((response) => {
console.log(response.message);
}
);
// function setupCounter(initialValue = 0) {
// document.getElementById('counter')!.innerHTML = initialValue.toString();
//
// document.getElementById('incrementBtn')!.addEventListener('click', () => {
// updateCounter({
// type: 'INCREMENT',
// });
// });
//
// document.getElementById('decrementBtn')!.addEventListener('click', () => {
// updateCounter({
// type: 'DECREMENT',
// });
// });
// }
//
// function updateCounter({ type }: { type: string }) {
// counterStorage.get((count: number) => {
// let newCount: number;
//
// if (type === 'INCREMENT') {
// newCount = count + 1;
// } else if (type === 'DECREMENT') {
// newCount = count - 1;
// } else {
// newCount = count;
// }
//
// counterStorage.set(newCount, () => {
// document.getElementById('counter')!.innerHTML = newCount.toString();
//
// // Communicate with content script of
// // active tab by sending a message
// browser.tabs.query({ active: true, currentWindow: true }).then((tabs) => {
// const tab = tabs[0];
//
// browser.tabs.sendMessage(
// tab.id!,
// {
// type: 'COUNT',
// payload: {
// count: newCount,
// },
// }).then((response) => {
// console.log('Current count value passed to contentScript file');
// }
// ).catch(console.error);
// });
// });
// });
// }
//
// function restoreCounter() {
// // Restore count value
// counterStorage.get((count: number) => {
// if (typeof count === 'undefined') {
// // Set counter value as 0
// counterStorage.set(0, () => {
// setupCounter(0);
// });
// } else {
// setupCounter(count);
// }
// });
// }
//
// document.addEventListener('DOMContentLoaded', restoreCounter);
//
// // Communicate with background file by sending a message
// browser.runtime.sendMessage(
// {
// type: 'GREETINGS',
// payload: {
// message: 'Hello, my name is Pop. I am from Popup.',
// },
// }).then((response) => {
// console.log(response.message);
// }
// );
})();

0 comments on commit 02ecf04

Please sign in to comment.