0

I have an extension that changes the value through a class. but it only works in popup.html. I want it to work for all pages. I've tried to change json manifestation but it still dont work. may be problem is in code. help me please =(

Javascript code:

function saveElementState(elementClasses, newValue) {
    const savedState = JSON.parse(localStorage.getItem('elementStates')) || {};
    savedState[elementClasses] = newValue;
    localStorage.setItem('elementStates', JSON.stringify(savedState));
}


function restoreElementStates() {
    const savedState = JSON.parse(localStorage.getItem('elementStates')) || {};
    for (const elementClasses in savedState) {
        const elements = document.getElementsByClassName(elementClasses);
        if (elements.length > 0) {
            elements[0].textContent = savedState[elementClasses];
        }
    }
}

document.addEventListener("click", function(event) {
    const clickedElement = event.target;
    const newValueInput = document.getElementById("newValue");
    const newValue = newValueInput.value;

    if (clickedElement.classList.contains("saveButton") && newValue !== "") {
        const elementClasses = prompt("Enter the element's classes:", "");
        if (elementClasses !== null && elementClasses !== "") {
            const elements = document.getElementsByClassName(elementClasses);
            if (elements.length > 0) {
                saveElementState(elementClasses, newValue);
           }
        }
    }
});

document.addEventListener("DOMContentLoaded", function() {
    restoreElementStates();
});

const clear = document.getElementById('clear');
clear.addEventListener('click', () => {
    localStorage.clear();
});

JSON manifestation:

{
  "manifest_version": 2,
 "name": "Element Value Changer",
  "version": "1.0",
  "description": "Change element values and save to local storage",
  "permissions": ["activeTab", "storage"],
  "content_scripts": [
   {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],
  "browser_action": {
    "default_popup": "popup.html"
  }
}
  • You need two files: 1) popup.js loaded in popup.html that works with your popup UI. 2) content.js that runs in the web pages. It shouldn't have anything related to the popup UI. You'll use messaging or chrome.storage to configure it if necessary. Note that the popup is a separate window so it has its own separate devtools: right-click inside the popup and select "inspect" in the menu. – wOxxOm Aug 20 '23 at 11:51

0 Answers0