Frontend Development 11 min read

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.

JD Cloud Developers
JD Cloud Developers
JD Cloud Developers
Build a Chrome Extension to Convert Timestamps in Seconds and Milliseconds

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.json

and

background.js

configure browser‑level behavior (name, description, context menu, etc.), while

popup.html

and

popup.js

define the UI and functionality. The browser and extension communicate via

background.js

and

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.js

defines 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.html

defines 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>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
  &lt;meta charset="UTF-8"&gt;
  &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
  &lt;title&gt;Convert Timestamp&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;h1&gt;Convert Timestamp&lt;/h1&gt;
  &lt;form id="inputQuery"&gt;
    &lt;input type="text" id="TimeInput" name="TimeInput" placeholder="Enter timestamp string" required&gt;
    &lt;button id="submitButton" type="button"&gt;OK&lt;/button&gt;
  &lt;/form&gt;
  &lt;div id="result"&gt;
    &lt;p&gt;Input TimeStamp String:&lt;/p&gt;
    &lt;p id="inStr"&gt;&lt;/p&gt;
    &lt;p&gt;Converted Time:&lt;/p&gt;
    &lt;p id="outStr"&gt;&lt;/p&gt;
  &lt;/div&gt;
  &lt;script src="popup.js"&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code>

4. Write popup.js

popup.js

handles interaction logic and communication with

background.js

. It listens for the

DOMContentLoaded

event to load the selected text, perform conversion, and display results. The button click triggers the

transForm

function 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.

JavaScriptFrontend Developmentchrome extensionTimestamp ConversionWeb Tools
JD Cloud Developers
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.