So I have a settings object which is configured by the options page in my extension. This stores the data in chrome.storage.local.
const DEFAULT_SETTINGS = {
css: {
test:true
}
}
let settings = { ...DEFAULT_SETTINGS };
// Function to load settings from chrome.storage.local
function loadSettings(callback) {
chrome.storage.local.get('settings', (result) => {
if (result.settings) {
settings = JSON.parse(result.settings);
}
if (callback) callback(settings);
});
}
// Function to save settings to chrome.storage.local
function saveSettings(callback) {
chrome.storage.local.set({ settings: JSON.stringify(settings) }, () => {
console.log('Settings saved:', settings);
if (callback) callback();
});
}
// Expose the functions and settings object
export { settings, loadSettings, saveSettings };
The options page has the following line so that it can use settings:
import { settings, loadSettings, saveSettings } from './settings.js';
This all works perfectly
My background script loads settings and also has a reference to the settings.js file and makes them available to content scripts via messaging
import { settings, loadSettings, saveSettings } from './settings.js';
/ Listen for messages from content scripts
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
switch (request.action) {
case "getSettings":
sendResponse({ settings });
break;
case "saveSettings":
settings = request.settings;
saveSettings(() => sendResponse({ status: "success" }));
break;
}
return true;
});
This all works fine.
The problem came when I tried to use settings.js in my content script
Adding the reference in my manifest
"content_scripts": [
{
"matches": ["http://localhost:8000/*", "https://www.amazon.co.uk/vine/vine-items*"],
"js": ["settings.js", "manicviner.js"],
"run_at": "document_start"
}
],
gave an error when I reloaded the extension as it didn’t like the export in settings.js
Removing the reference does allow me to pass settings into the content script via messaging
chrome.runtime.sendMessage({ action: "getSettings" }, (response) => {
const mysettings = response.settings;
console.log(mysettings); // Now you can use the settings
});
However it is just the JSON that comes back – I cannot use the settings object itself because the content script has no knowledge of the object structure.
Apparently ES6 modules cannot be used in content scripts – which is the root of the issue here. SO how can I structure my code so that when I use settings in my content script I have access to the object model as defined in settings.js? e.g. settings.css.test