0

I made a toggle button in my popup that switches from popup_0.html (default popup) to popup_1.html. If the toggle is off: popup_0.html is used. If the toggle is on: popup_1.html is use.

My problem is that the switching of the popup is not instant, the popup still needs to be close and reopen in order to see the new popup. How can I code this to make the popup switching instant without the need to close and reopen? I used setPopup, should I even consider a toggle that use an a-tag in html instead?

This is sort of a turn on and off button for my chrome extension. I'm new in developing a chrome extension, help me out! :)

popup_0.html:

<label class="switch">
        <input type="checkbox">
        <span class="slider">
         <svg class="slider-icon" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="presentation"><path fill="none" d="m4 16.5 8 8 16-16"></path></svg> 
        </span>
      </label>

popup.js:

const slider = document.querySelector('.slider');
const checkbox = document.querySelector('input[type="checkbox"]');

function setSliderBackground(checked) {
  slider.style.backgroundColor = checked ? 'green' : '#B0B0B0';
}

function setPopupHtml(checked) {
  const popupHtml = checked ? 'popup_1.html' : 'popup_0.html';
  chrome.action.setPopup({ popup: popupHtml });
}

function toggleCheckbox() {
  const checked = checkbox.checked;
  setSliderBackground(checked);
  setPopupHtml(checked);
  chrome.storage.sync.set({ checked });
}

function loadToggleStateFromStorage() {
  chrome.storage.sync.get('checked', ({ checked }) => {
    checkbox.checked = checked;
    setSliderBackground(checked);
    setPopupHtml(checked); // Set the popup HTML after the toggle state is loaded
  });
}

checkbox.addEventListener('change', toggleCheckbox);
loadToggleStateFromStorage();

css:


.switch {
  font-size: 17px;
  position: relative;
  display: inline-block;
  width: 3em;
  height: 1.5em;
  left: 2em;

}

/* Hide default HTML checkbox */
.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

/* The slider */
.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #B0B0B0;
  border: 1px solid #B0B0B0;
  transition: .4s;
  border-radius: 32px;
  outline: none;
  box-shadow: inset 3px 3px 5px rgba(0,0,0);

}

.slider:before {
  position: absolute;
  content: "";
  height: 1.5rem;
  width: 1.5rem;
  border-radius: 50%;
  outline: 2px solid #B0B0B0;
  left: -1px;
  bottom: -1px;
  background-color: #fff;
  transition: transform .25s ease-in-out 0s;
}


input:checked + .slider {
  background-color: #0C0B37;
}

input:checked + .slider .slider-icon {
  opacity: 1;
  right: 20%;
}

input:checked + .slider:before {
  transform: translateX(1.5em);
  outline-color: #181818;
}


Benz Tagle
  • 33
  • 3

0 Answers0