Creating a Chrome extension that adds a "Format LaTeX" option to the context menu, validates the selected LaTeX expression, and displays it using MathJax in an injected modal involves several steps. Below is a comprehensive guide to help you build this extension using Manifest V3, Chrome's latest extension format.
Table of Contents
- Project Structure
- Creating
manifest.json
- Background Script: Adding Context Menu
- Content Script: Handling Modal and LaTeX Rendering
- Including MathJax
- Validating LaTeX Expressions
- Styling the Modal
- Putting It All Together
- Testing the Extension
1. Project Structure
Create a project directory with the following structure:
latex-formatter/
│
├── manifest.json
├── background.js
├── content.js
├── modal.css
└── icons/
└── icon.png
You can customize the icon as needed.
2. Creating manifest.json
The manifest.json file is the blueprint of your Chrome extension. For Manifest V3, it should include necessary permissions and specify background and content scripts.
{
"manifest_version": 3,
"name": "LaTeX Formatter",
"version": "1.0",
"description": "Format selected LaTeX expressions using MathJax.",
"permissions": [
"contextMenus",
"scripting"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"css": ["modal.css"],
"run_at": "document_idle"
}
],
"icons": {
"16": "icons/icon.png",
"48": "icons/icon.png",
"128": "icons/icon.png"
}
}
Explanation of Key Fields:
3. Background Script: Adding Context Menu
The background script is responsible for adding the "Format LaTeX" option to the context menu and handling its click events.
Create background.js:
// background.js
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "formatLatex",
title: "Format LaTeX",
contexts: ["selection"]
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "formatLatex") {
const text = info.selectionText;
chrome.tabs.sendMessage(tab.id, { action: "formatLatex", text: text });
}
});
Explanation:
- onInstalled: Ensures the context menu item is created when the extension is installed.
- onClicked: Listens for clicks on the custom context menu item and sends a message to the content script with the selected text.
4. Content Script: Handling Modal and LaTeX Rendering
The content script listens for messages from the background script, validates the LaTeX expression, and displays the modal with the rendered output or error message.
Create content.js:
// content.js
// Listen for messages from the background script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "formatLatex") {
const latexText = request.text;
showModal(latexText);
}
});
// Function to create and display the modal
function showModal(latexText) {
// Remove existing modal if any
const existingModal = document.getElementById("latex-formatter-modal");
if (existingModal) {
existingModal.remove();
}
// Create modal elements
const modal = document.createElement("div");
modal.id = "latex-formatter-modal";
modal.innerHTML = `
<div class="lf-modal-content">
<span class="lf-close-button">×</span>
<div class="lf-modal-body">
<div id="lf-rendered-content"></div>
<div id="lf-error-message" style="color: red;"></div>
</div>
</div>
`;
document.body.appendChild(modal);
// Close functionality
modal.querySelector(".lf-close-button").addEventListener("click", () => {
modal.remove();
});
// Validate and render LaTeX
validateAndRender(latexText);
}
// Function to validate LaTeX expression
function validateAndRender(latexText) {
const renderedContent = document.getElementById("lf-rendered-content");
const errorMessage = document.getElementById("lf-error-message");
// Clear previous content
renderedContent.innerHTML = "";
errorMessage.textContent = "";
try {
// Escape dollar signs for MathJax
const escapedText = latexText.replace(/$/g, '\\$');
// Create script tag for MathJax processing
const script = document.createElement("script");
script.type = "math/tex";
script.text = escapedText;
renderedContent.appendChild(script);
// Configure MathJax
if (!window.MathJax) {
// Inject MathJax if not already present
const mathJaxScript = document.createElement("script");
mathJaxScript.src = "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js";
mathJaxScript.async = true;
mathJaxScript.onload = () => {
MathJax.typesetPromise([renderedContent]).then(() => {
// Check if MathJax rendered any content
if (renderedContent.textContent.trim() === "") {
throw new Error("Invalid LaTeX expression.");
}
}).catch((err) => {
renderedContent.innerHTML = "";
errorMessage.textContent = "Invalid LaTeX expression.";
console.error(err);
});
};
document.head.appendChild(mathJaxScript);
} else {
// If MathJax is already loaded
MathJax.typesetPromise([renderedContent]).then(() => {
if (renderedContent.textContent.trim() === "") {
throw new Error("Invalid LaTeX expression.");
}
}).catch((err) => {
renderedContent.innerHTML = "";
errorMessage.textContent = "Invalid LaTeX expression.";
console.error(err);
});
}
} catch (error) {
errorMessage.textContent = "Invalid LaTeX expression.";
console.error(error);
}
}
Explanation:
-
Message Listener: Listens for the "formatLatex" action and retrieves the selected text.
-
Modal Creation (showModal):
- Creates a modal overlay with a close button.
- Injects necessary HTML structure for displaying the rendered LaTeX or error messages.
-
Validation and Rendering (validateAndRender):
- Attempts to render the LaTeX expression using MathJax.
- If MathJax is not already loaded on the page, it injects the MathJax script.
- Uses
MathJax.typesetPromise to process the LaTeX.
- If rendering fails or produces no content, it displays an error message.
Note: This approach assumes that the selected text is intended to be a LaTeX math expression. You might want to enhance validation based on specific requirements.
5. Including MathJax
MathJax is essential for rendering LaTeX expressions. The content script handles loading MathJax if it's not already present on the page.
Using CDN:
In the validateAndRender function within content.js, MathJax is loaded via a CDN:
mathJaxScript.src = "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js";
Alternatively, Bundling MathJax Locally:
For better performance and offline support, you might consider bundling MathJax with your extension. However, keep in mind that MathJax is quite large (~2MB), which might increase your extension's size.
6. Validating LaTeX Expressions
Validating LaTeX expressions programmatically can be complex. The approach used here attempts to render the expression with MathJax and catches any errors that occur during the process. If rendering fails or produces no output, the expression is considered invalid.
Enhancements:
- Syntax Checking: Implement or integrate a LaTeX parser to perform syntax checking without rendering.
- User Feedback: Provide more detailed error messages based on parsing/rendering errors.
Due to complexity, the current implementation uses rendering as a validation method.
7. Styling the Modal
To ensure the modal looks good and is user-friendly, add appropriate CSS styles.
Create modal.css:
/* modal.css */
#latex-formatter-modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 10000;
}
.lf-modal-content {
background-color: #fefefe;
padding: 20px;
border-radius: 8px;
width: 80%;
max-width: 500px;
position: relative;
box-shadow: 0 5px 15px rgba(0,0,0,.5);
}
.lf-close-button {
position: absolute;
top: 10px;
right: 15px;
color: #aaa;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
.lf-close-button:hover,
.lf-close-button:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
.lf-modal-body {
margin-top: 30px;
}
#lf-rendered-content {
font-size: 18px;
}
Explanation:
- Overlay (
#latex-formatter-modal): Covers the entire viewport with a semi-transparent background.
- Modal Content (
.lf-modal-content): Centers the modal with padding, border-radius, and shadow for better aesthetics.
- Close Button (
.lf-close-button): Positioned at the top-right corner of the modal.
- Modal Body (
.lf-modal-body): Contains the rendered LaTeX or error messages.
8. Putting It All Together
Ensure all parts are correctly referenced and interact seamlessly.
Final manifest.json:
Make sure modal.css is included in the content_scripts array.
{
"manifest_version": 3,
"name": "LaTeX Formatter",
"version": "1.0",
"description": "Format selected LaTeX expressions using MathJax.",
"permissions": [
"contextMenus",
"scripting"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"],
"css": ["modal.css"],
"run_at": "document_idle"
}
],
"icons": {
"16": "icons/icon.png",
"48": "icons/icon.png",
"128": "icons/icon.png"
}
}
Ensure File Paths Are Correct:
- Icons: Place your icon images in the
icons/ directory.
- Scripts and CSS: All scripts and CSS files should be in the root directory unless specified otherwise.
9. Testing the Extension
-
Load the Extension in Chrome:
- Open
chrome://extensions/ in your Chrome browser.
- Enable "Developer mode" using the toggle in the top-right corner.
- Click "Load unpacked" and select your
latex-formatter project directory.
-
Verify Installation:
- Ensure the extension appears in your list and the icon is visible.
-
Test Functionality:
- Navigate to any webpage.
- Select a LaTeX math expression in the text (e.g.,
$\frac{a}{b}$ or \int_{0}^{1} x^2 dx).
- Right-click to open the context menu.
- Click on "Format LaTeX".
- A modal should appear displaying the rendered LaTeX expression.
- Test with both valid and invalid LaTeX expressions to ensure error handling works.
-
Debugging:
- If the modal doesn't appear or LaTeX isn't rendered, check the console for errors.
- Open DevTools for the webpage (
F12 or Ctrl+Shift+I) and inspect the console logs.
- Ensure that MathJax is loading correctly and that there are no CORS issues or script loading errors.
Additional Enhancements
-
Improved Validation:
- Integrate a LaTeX parsing library to provide more precise error messages.
-
Customization Options:
- Allow users to customize the appearance of the modal or choose different rendering options.
-
Performance Optimization:
- Cache MathJax after the first load to prevent multiple injections on the same page.
-
Accessibility:
- Ensure the modal is accessible via keyboard navigation and screen readers.
-
Internationalization:
- Support multiple languages for error messages and UI elements.
-
Security Considerations:
- Sanitize user input to prevent potential XSS attacks, especially if rendering user-generated content.
By following this guide, you should have a functional Chrome extension that formats selected LaTeX expressions using MathJax within an injected modal, providing users with immediate visual feedback. Customize and enhance the extension further based on your specific needs and use cases.