Sure! I'll help you rewrite the code for Firefox, adapting it to Firefox's extension APIs and practices, and also extend the HTML acceleration functionality as per your requirements.
Overview
- Adapt the code for Firefox Extensions: We'll replace
chrome API calls with browser APIs where necessary and adjust for any differences in the extension environment.
- Injecting Scripts into the Page Context: In Firefox, content scripts run in a separate context from the page's JavaScript context. To modify page functions like
setTimeout, setInterval, etc., we'll inject a script into the page.
- Extend the HTML Acceleration Functionality: We'll add an example of extending functionality, such as adding the ability to control CSS animation speed.
Files Structure
We'll organize the code into separate files:
manifest.json: Extension manifest file.
background.js: Background script for handling configurations.
content_script.js: Content script injected into web pages.
page_script.js: Script injected into the page context to override functions.
- Optionally, you can have
options.html and options.js if you want to add a user interface for settings.
1. manifest.json
{
"manifest_version": 2,
"name": "Firefox Speed Control Extension",
"version": "1.0",
"description": "Control the speed of webpage functions.",
"permissions": [
"tabs",
"activeTab",
"storage"
],
"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content_script.js"],
"run_at": "document_start"
}
],
"web_accessible_resources": [
"page_script.js"
],
"options_ui": {
"page": "options.html",
"open_in_tab": false
}
}
2. background.js
// background.js
let speedConfig = {
speed: 1.0,
cbSetIntervalChecked: true,
cbSetTimeoutChecked: true,
cbPerformanceNowChecked: true,
cbDateNowChecked: true,
cbRequestAnimationFrameChecked: false,
cbCssAnimationChecked: false // New option for CSS animations
};
// Listen for messages from the content script or options page
browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.command === 'getSpeedConfig') {
sendResponse(speedConfig);
} else if (request.command === 'setSpeedConfig') {
speedConfig = request.config;
// Save the configuration to storage
browser.storage.local.set({ speedConfig });
// Notify all tabs about the updated configuration
browser.tabs.query({}, (tabs) => {
for (let tab of tabs) {
browser.tabs.sendMessage(tab.id, {
command: 'setSpeedConfig',
config: speedConfig
});
}
});
sendResponse({ status: 'success' });
}
});
3. content_script.js
// content_script.js
let speedConfig = {};
// Inject the page script into the page
const script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', browser.runtime.getURL('page_script.js'));
(document.head || document.documentElement).appendChild(script);
script.remove();
// Relay messages between the page script and the background script
window.addEventListener('message', (e) => {
if (e.source !== window) {
return;
}
if (e.data.command === 'getSpeedConfig') {
// Send the speedConfig to the page
window.postMessage({
command: 'setSpeedConfig',
config: speedConfig,
}, '*');
} else if (e.data.command === 'setSpeedConfig') {
// Update local speedConfig
speedConfig = e.data.config;
// Send updated config to background script
browser.runtime.sendMessage({
command: 'setSpeedConfig',
config: speedConfig
});
}
});
// Listen for messages from the background script
browser.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.command == 'setSpeedConfig') {
speedConfig = request.config;
// Forward the updated config to the page script
window.postMessage({
command: 'setSpeedConfig',
config: speedConfig
}, '*');
} else if (request.command == 'getSpeedConfig') {
sendResponse(speedConfig);
}
});
// Get the initial configuration from storage
browser.storage.local.get('speedConfig', (result) => {
speedConfig = result.speedConfig || {
speed: 1.0,
cbSetIntervalChecked: true,
cbSetTimeoutChecked: true,
cbPerformanceNowChecked: true,
cbDateNowChecked: true,
cbRequestAnimationFrameChecked: false,
cbCssAnimationChecked: false
};
});
4. page_script.js
// page_script.js
(function () {
let speedConfig = {
speed: 1.0,
cbSetIntervalChecked: true,
cbSetTimeoutChecked: true,
cbPerformanceNowChecked: true,
cbDateNowChecked: true,
cbRequestAnimationFrameChecked: false,
cbCssAnimationChecked: false // New option for CSS animations
};
const emptyFunction = () => {};
const originalClearInterval = window.clearInterval;
const originalClearTimeout = window.clearTimeout;
const originalSetInterval = window.setInterval;
const originalSetTimeout = window.setTimeout;
const originalPerformanceNow = window.performance.now.bind(window.performance);
const originalDateNow = Date.now;
const originalRequestAnimationFrame = window.requestAnimationFrame;
let timers = [];
const reloadTimers = () => {
// Implement your logic to reload timers with the new speed
// Similar to your original code
};
// Listen for messages from the content script
window.addEventListener("message", (e) => {
if (e.data.command === "setSpeedConfig") {
speedConfig = e.data.config;
reloadTimers();
// Apply CSS animation speed control if enabled
if (speedConfig.cbCssAnimationChecked) {
document.documentElement.style.setProperty('--animation-speed', speedConfig.speed);
} else {
document.documentElement.style.removeProperty('--animation-speed');
}
} else if (e.data.command === "getSpeedConfig") {
// Send speedConfig back
window.postMessage(
{
command: "setSpeedConfig",
config: speedConfig,
},
"*"
);
}
});
// Request the initial speed configuration
window.postMessage({ command: "getSpeedConfig" }, "*");
// Override setInterval
window.setInterval = function (handler, timeout, ...args) {
// Your existing logic to control setInterval
};
// Override setTimeout
window.setTimeout = function (handler, timeout, ...args) {
// Your existing logic to control setTimeout
};
// Override performance.now
(function () {
// Your existing logic to control performance.now
})();
// Override Date.now
(function () {
// Your existing logic to control Date.now
})();
// Override requestAnimationFrame
(function () {
// Your existing logic to control requestAnimationFrame
})();
// **New Functionality**: Control CSS Animations
if (speedConfig.cbCssAnimationChecked) {
// Inject a style element to control CSS animations
const style = document.createElement('style');
style.innerHTML = `
* {
animation-duration: calc(var(--animation-speed, 1) * 1s) !important;
transition-duration: calc(var(--animation-speed, 1) * 1s) !important;
}
`;
document.head.appendChild(style);
}
})();
5. Extend HTML Acceleration Functionality
Example: Adding control over CSS animation speed.
- In
speedConfig, we added a new option cbCssAnimationChecked to control whether CSS animations are accelerated.
- In
page_script.js, we inject a <style> element that modifies the animation-duration and transition-duration properties globally, scaling them by --animation-speed.
- When the speed is changed, we update the CSS variable
--animation-speed to the new speed value.
6. options.html (Optional)
Create an options page where users can adjust the speed and select which functions to control.
<!-- options.html -->
<!DOCTYPE html>
<html>
<head>
<title>Speed Control Extension Options</title>
</head>
<body>
<h1>Speed Control Settings</h1>
<label>
Speed:
<input type="number" id="speed" min="0.1" max="10" step="0.1" value="1.0">
</label>
<br>
<label>
<input type="checkbox" id="cbSetIntervalChecked" checked>
Control setInterval
</label>
<br>
<label>
<input type="checkbox" id="cbSetTimeoutChecked" checked>
Control setTimeout
</label>
<br>
<label>
<input type="checkbox" id="cbPerformanceNowChecked" checked>
Control performance.now
</label>
<br>
<label>
<input type="checkbox" id="cbDateNowChecked" checked>
Control Date.now
</label>
<br>
<label>
<input type="checkbox" id="cbRequestAnimationFrameChecked">
Control requestAnimationFrame
</label>
<br>
<label>
<input type="checkbox" id="cbCssAnimationChecked">
Control CSS Animations
</label>
<br>
<button id="save">Save</button>
<script src="options.js"></script>
</body>
</html>
7. options.js (Optional)
// options.js
document.addEventListener('DOMContentLoaded', function () {
const speedInput = document.getElementById('speed');
const cbSetIntervalChecked = document.getElementById('cbSetIntervalChecked');
const cbSetTimeoutChecked = document.getElementById('cbSetTimeoutChecked');
const cbPerformanceNowChecked = document.getElementById('cbPerformanceNowChecked');
const cbDateNowChecked = document.getElementById('cbDateNowChecked');
const cbRequestAnimationFrameChecked = document.getElementById('cbRequestAnimationFrameChecked');
const cbCssAnimationChecked = document.getElementById('cbCssAnimationChecked');
// Load saved settings
browser.storage.local.get('speedConfig', (result) => {
const config = result.speedConfig || {
speed: 1.0,
cbSetIntervalChecked: true,
cbSetTimeoutChecked: true,
cbPerformanceNowChecked: true,
cbDateNowChecked: true,
cbRequestAnimationFrameChecked: false,
cbCssAnimationChecked: false
};
speedInput.value = config.speed;
cbSetIntervalChecked.checked = config.cbSetIntervalChecked;
cbSetTimeoutChecked.checked = config.cbSetTimeoutChecked;
cbPerformanceNowChecked.checked = config.cbPerformanceNowChecked;
cbDateNowChecked.checked = config.cbDateNowChecked;
cbRequestAnimationFrameChecked.checked = config.cbRequestAnimationFrameChecked;
cbCssAnimationChecked.checked = config.cbCssAnimationChecked;
});
// Save settings
document.getElementById('save').addEventListener('click', () => {
const config = {
speed: parseFloat(speedInput.value),
cbSetIntervalChecked: cbSetIntervalChecked.checked,
cbSetTimeoutChecked: cbSetTimeoutChecked.checked,
cbPerformanceNowChecked: cbPerformanceNowChecked.checked,
cbDateNowChecked: cbDateNowChecked.checked,
cbRequestAnimationFrameChecked: cbRequestAnimationFrameChecked.checked,
cbCssAnimationChecked: cbCssAnimationChecked.checked
};
// Send the new configuration to the background script
browser.runtime.sendMessage({ command: 'setSpeedConfig', config }, (response) => {
if (response.status === 'success') {
alert('Settings saved successfully!');
} else {
alert('Failed to save settings.');
}
});
});
});
Notes:
- Browser Compatibility: In Firefox extensions, you can use
browser or chrome; however, browser is recommended as it returns promises, which are more manageable.
- Content Security Policy (CSP): Injecting inline scripts can be restricted. By including
page_script.js in web_accessible_resources and injecting it via a <script src="">, we avoid CSP issues.
- Accessing Page Context: By injecting
page_script.js into the page, we can override the page's functions directly.
- Communication Between Scripts: We use
window.postMessage to communicate between the page script and the content script, and browser.runtime.sendMessage between the content script and the background script.
Extending Functionality
The provided code extends the functionality by controlling CSS animations. You can further extend it by:
- Controlling Other Global Functions: Override other global functions as needed.
- Adding User Interface Elements: Allow users to adjust settings via a popup or options page.
- Domain-Specific Settings: Apply different settings based on the domain or URL.
Final Thoughts
This rewritten code adapts your original code to work in Firefox and demonstrates how to extend the HTML acceleration functionality. You can further customize and extend this example based on your specific requirements.