Build a Chrome Extension to Convert Timestamps in Seconds and Milliseconds
This article walks through the design, implementation, and debugging of a Chrome extension that converts timestamps between seconds, milliseconds, and human‑readable date‑time formats, covering manifest setup, background scripts, popup UI, and JavaScript logic.
Inspired by the article "Everyone Can Write a Chrome Extension and Save Over 1000 Yuan," I learned some frontend basics and, driven by work needs, decided to create a Chrome extension for timestamp conversion.
1. Plugin Concept
1. How to use the plugin:
Referencing a frequently used plugin, the most efficient usage is to select a string in the console, right‑click, and let the plugin display formatted data, skipping copy‑paste steps. The new plugin should allow selecting a time‑format string and converting it directly, as well as supporting manual input.
2. Required features:
For backend testing, scenarios include comparing page timestamps with MQ timestamps and generating timestamps. The plugin must handle second‑level and millisecond‑level timestamps and convert between timestamps and year‑month‑day hour:minute:second formats.
2. Implementation Steps
Create a folder with four files:
manifest.json(required),
background.js,
popup.html, and
popup.js.
manifest.jsonand
background.jsconfigure browser‑level behavior (name, description, context menu, etc.), while
popup.htmland
popup.jsdefine the UI and functionality. The browser and extension communicate via
background.jsand
popup.js.
1. Write manifest.json
The manifest file is mandatory for Chrome extensions and includes basic information such as name, version, and description. Note that newer Chrome versions only support
manifest_version=3.
<code>{
"manifest_version": 3,
"name": "TimeStamp-Handle",
"version": "1.0",
"description": "支持时间戳、年月日时分秒自动转换",
"permissions": [
"contextMenus",
"storage"
],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html"
}
}</code>2. Write background.js
background.jsdefines the extension's behavior, such as capturing selected text, adding a context‑menu item, and opening the popup. Using
chrome.runtime.getURL("popup.html")avoids errors caused by
chrome.action.openPopup().
<code>// Define behavior
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "TimeStampTrans",
title: "Convert Timestamp",
contexts: ["selection"]
});
});
// Message passing
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "TimeStampTrans") {
chrome.storage.local.set({ selectedText: info.selectionText }, () => {
chrome.windows.create({
url: chrome.runtime.getURL("popup.html")
});
});
}
});
</code>3. Write popup.html
popup.htmldefines the UI shown in the popup, containing an input box, a button, and a result area. Due to Chrome security policies, button listeners are handled in the script.
<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Convert Timestamp</title>
</head>
<body>
<h1>Convert Timestamp</h1>
<form id="inputQuery">
<input type="text" id="TimeInput" name="TimeInput" placeholder="Enter timestamp string" required>
<button id="submitButton" type="button">OK</button>
</form>
<div id="result">
<p>Input TimeStamp String:</p>
<p id="inStr"></p>
<p>Converted Time:</p>
<p id="outStr"></p>
</div>
<script src="popup.js"></script>
</body>
</html>
</code>4. Write popup.js
popup.jshandles interaction logic and communication with
background.js. It listens for the
DOMContentLoadedevent to load the selected text, perform conversion, and display results. The button click triggers the
transFormfunction for manual input.
<code>function changeMain(timeString) { //2024-10-28 15:30:46
if (timeString.length == 19) {
// Convert date‑time to timestamps
var time1 = new Date(timeString).getTime(); // milliseconds
var time2 = new Date(timeString).getTime() / 1000; // seconds
return [time1, time2];
} else if (timeString.length == 10) {
// Seconds to date‑time
var date = new Date(Number(timeString) * 1000);
var year = date.getFullYear();
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + date.getDate()).slice(-2);
var hours = ("0" + date.getHours()).slice(-2);
var minutes = ("0" + date.getMinutes()).slice(-2);
var seconds = ("0" + date.getSeconds()).slice(-2);
return [`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`];
} else if (timeString.length == 13) {
// Milliseconds to date‑time
var date = new Date(Number(timeString));
var year = date.getFullYear();
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + date.getDate()).slice(-2);
var hours = ("0" + date.getHours()).slice(-2);
var minutes = ("0" + date.getMinutes()).slice(-2);
var seconds = ("0" + date.getSeconds()).slice(-2);
return [`${year}-${month}-${day} ${hours}:${minutes}:${seconds}`];
} else {
return ["非时间格式"];
}
}
// Communication handling
document.addEventListener('DOMContentLoaded', () => {
chrome.storage.local.get('selectedText', (data) => {
document.getElementById('inStr').innerText = data.selectedText;
var result = changeMain(data.selectedText);
document.getElementById('outStr').innerText = result;
});
// Button click handling
document.querySelector('button').addEventListener('click', transForm, false);
});
// Opened directly as a page
function transForm() {
var inputString = document.getElementById('TimeInput').value;
var result = changeMain(inputString);
document.getElementById('inStr').innerText = inputString;
document.getElementById('outStr').innerText = result;
}
</code>3. Debugging and Usage
Open Chrome Settings → Extensions → enable Developer Mode → Load unpacked extension → select the extension folder.
After loading, the extension can be used directly. When modifying code, simply refresh the extension without removing it. If errors occur, they appear next to the Remove button.
JD Cloud Developers
JD Cloud Developers (Developer of JD Technology) is a JD Technology Group platform offering technical sharing and communication for AI, cloud computing, IoT and related developers. It publishes JD product technical information, industry content, and tech event news. Embrace technology and partner with developers to envision the future.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.