Works by selecting text, then pressing Shift+Alt+R
Should open a modal (sleek dark design)
The modal should have the selected LaTeX, but formatted (using MathJax)
Works on "*" (every website)
Assistant
Below is the complete Tampermonkey script that allows you to select LaTeX expressions on any website and render them in a sleek dark-themed modal by pressing Shift + Alt + R. The script uses MathJax to render the LaTeX expressions.
javascript
// ==UserScript==
// @name Render LaTeX
// @namespace http://tampermonkey.net/
// @version 1.0
// @description Render unrendered LaTeX math expressions (Select expression; Shift+Alt+R)
// @author You
// @match *://*/*
// @grant GM_addStyle
// ==/UserScript==
(function() {
'use strict';
// Add necessary CSS for the modal
GM_addStyle(`
/* Modal Overlay */
#latex-render-modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.8);
display: flex;
align-items: center;
justify-content: center;
z-index: 10000;
}
/* Modal Content */
#latex-render-modal-content {
background: #2d2d2d;
padding: 20px;
border-radius: 8px;
max-width: 90%;
max-height: 90%;
overflow: auto;
position: relative;
box-shadow: 0 5px 15px rgba(0,0,0,0.3);
}
/* Close Button */
#latex-render-modal-close {
position: absolute;
top: 10px;
right: 15px;
background: transparent;
border: none;
color: #fff;
font-size: 1.5em;
cursor: pointer;
}
/* Optional: Smooth fade-in animation */
#latex-render-modal-overlay {
animation: fadeIn 0.3s ease-out;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
`);
// Function to load MathJax if not already loaded
function loadMathJax(callback) {
if (window.MathJax) {
callback();
return;
}
// Load MathJax script
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js';
script.async = true;
script.onload = () => {
window.MathJax = {
tex: {
inlineMath: [['$', '$'], ['\\(', '\\)']]
},
svg: {
fontCache: 'global'
}
};
// Wait for MathJax to initialize
script.onload = null;
callback();
};
document.head.appendChild(script);
}
// Function to create and show the modal
function showModal(latex) {
// Create overlay
const overlay = document.createElement('div');
overlay.id = 'latex-render-modal-overlay';
// Create modal content container
const modalContent = document.createElement('div');
modalContent.id = 'latex-render-modal-content';
// Create close button
const closeButton = document.createElement('button');
closeButton.id = 'latex-render-modal-close';
closeButton.innerHTML = '×';
closeButton.addEventListener('click', () => {
document.body.removeChild(overlay);
});
// Create LaTeX container
const latexContainer = document.createElement('div');
latexContainer.style.color = '#fff';
latexContainer.style.fontSize = '1.2em';
// Wrap the LaTeX in $$ for display mode
latexContainer.textContent = `$$${latex}$$`;
// Append elements
modalContent.appendChild(closeButton);
modalContent.appendChild(latexContainer);
overlay.appendChild(modalContent);
document.body.appendChild(overlay);
// Typeset the LaTeX using MathJax
window.MathJax.typesetPromise([latexContainer]).catch((err) => {
console.error('MathJax typeset failed: ', err);
latexContainer.textContent = 'Error rendering LaTeX.';
});
// Close modal when clicking outside the content
overlay.addEventListener('click', (e) => {
if (e.target === overlay) {
document.body.removeChild(overlay);
}
});
// Allow closing with the Escape key
const escListener = (e) => {
if (e.key === 'Escape') {
if (document.body.contains(overlay)) {
document.body.removeChild(overlay);
document.removeEventListener('keydown', escListener);
}
}
};
document.addEventListener('keydown', escListener);
}
// Keydown listener for Shift + Alt + R
document.addEventListener('keydown', (e) => {
// Check for Shift + Alt + R (case-insensitive)
if (e.shiftKey && e.altKey && (e.key === 'R' || e.key === 'r')) {
e.preventDefault(); // Prevent default action
const selection = window.getSelection().toString().trim();
if (!selection) {
// Optionally, you can provide feedback that nothing was selected
console.log('No text selected for LaTeX rendering.');
return;
}
// Load MathJax and then show the modal
loadMathJax(() => {
showModal(selection);
});
}
});
})();
Explanation of the Script:
Metadata Block:
@name, @version, @description, and other fields describe the script.
@match *://*/* ensures the script runs on all websites.
@grant GM_addStyle allows the script to inject custom CSS.
CSS Styling (GM_addStyle):
Styles for the modal overlay and content are injected to ensure the modal has a sleek dark design.
The modal overlay covers the entire viewport with a semi-transparent dark background.
The modal content is centered, with padding, rounded corners, and a close button.
A fade-in animation enhances the user experience.
Loading MathJax:
The loadMathJax function checks if MathJax is already loaded. If not, it dynamically injects the MathJax script from the CDN.
After loading, it configures MathJax to recognize standard inline and display math delimiters.
It ensures that MathJax is ready before attempting to render the LaTeX.
Creating and Displaying the Modal (showModal):
Constructs the modal elements (overlay, modalContent, closeButton, and latexContainer).
The selected LaTeX text is placed inside the modal, wrapped with $$ to denote display math mode.
MathJax processes the LaTeX expression to render it properly.
The modal can be closed by clicking the close button, clicking outside the modal content, or pressing the Escape key.
Keyboard Shortcut Listener:
The script listens for the keydown event.
If Shift + Alt + R is pressed, it prevents the default browser behavior.
It retrieves the currently selected text. If there's no selection, it logs a message to the console (you can modify this to show a user-facing notification if desired).
If there is selected text, it loads MathJax (if not already loaded) and displays the modal with the rendered LaTeX.
Usage Instructions:
Installation:
Ensure you have the Tampermonkey extension installed in your browser.
Click on the Tampermonkey icon and select "Create a new script".
Replace the default script content with the script provided above.
Save the script.
Rendering LaTeX:
Navigate to any website.
Select the LaTeX expression you want to render.
Press Shift + Alt + R.
A dark modal will appear displaying the rendered LaTeX expression.
You can close the modal by clicking the close (×) button, clicking outside the modal content, or pressing the Escape key.
Notes:
MathJax Loading Time: On the first use, loading MathJax might take a moment, especially on slower connections. Subsequent uses should be faster since MathJax will be cached.
Security Considerations: Since the script runs on all websites, ensure that the selected LaTeX content is safe and doesn't contain any malicious code. However, the script sanitizes input by treating it as plain text and only renders it via MathJax.
Customization: Feel free to modify the CSS within the GM_addStyle block to better fit your aesthetic preferences or to adjust the modal's behavior.
This script should enhance your browsing experience by allowing quick and easy rendering of LaTeX expressions across any website.