0

I'm working on a chrome extension where I want to communicate between content script and injected html code & script, I'm trying to load images into the injected html, For that I want to send the absolute url from the content script to the inject html of the svg icon, But whenever I emit custom events on youtube the screen goes completely blank & also on other sites like stack overflow I saw that the images get refreshed, Is there a workaround this or am I doing something wrong?

Content Script

var s = undefined;

const images = [
  "/assets/icons/write.svg",
  "/assets/icons/write.svg",
  "/assets/icons/write.svg",
  "/assets/icons/write.svg",
  "/assets/icons/write.svg",
  "/assets/icons/write.svg",
  "/assets/icons/write.svg",
  "/assets/icons/write.svg",
];

const imageIds = [
  "#create-note",
  "#save-page",
  "#crop-webpage",
  "#save-images",
  "#bookmark-page",
  "#inspect-css",
  "#record-video",
  "#idk",
];

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log("heyoooo");
  if (request.message == "openPopup") {
    console.log("Open popup");
    s = document.createElement("script");
    s.src = chrome.runtime.getURL("js/app.js");
    s.onload = function () {
      for (var i = 0; i < images.length; i++) {
        const id = imageIds[i];
        const url = chrome.runtime.getURL(`${images[i]}`);
        var evt = document.createEvent("Event");
        evt.initEvent("imageUrl", true, true, { id, url });
        document.dispatchEvent(evt);
      }
    };
    document.body.appendChild(s);
    document.getElementsByTagName("body")[0].innerHTML += request.payload;
  } else if (request.message == "closePopup") {
    console.log("Close popup");
    document.getElementsByClassName("keep-it-app-container")[0].remove();
  }
});

Injected app.js script

var user = {};

document.addEventListener("imageUrl", function (e) {
  console.log(e);
});

Background script

var userLoggedIn = {};
const openTabs = [];
const apiUrl = "http://localhost:5000";
var popupOpen = false;
var currentWindow = undefined;

window.onload = () => {
  popupOpen = false;
};

chrome.storage.local.get("token", function (result) {
  userLoggedIn = result.token;
  chrome.windows.getCurrent((w) => {
    chrome.tabs.query(
      {
        windowId: w.id,
      },
      function (tabs) {
        openTabs.push(...tabs);
      }
    );
  });

  chrome.tabs.onCreated.addListener((tab) => {
    tab["popupOpen"] = false;
    openTabs.push(tab);
  });

  chrome.tabs.onRemoved.addListener((id, removeInfo) => {
    var indexOfTab = getIndexOfTab(id, openTabs);
    openTabs.splice(indexOfTab, 1);
  });

  chrome.tabs.onUpdated.addListener((id, changeInfo, tab) => {});

  chrome.tabs.onAttached.addListener((tabId, attachInfo) => {
    openTabs.push({
      id: tabId,
      popupOpen: false,
    });
  });

  chrome.tabs.onDetached.addListener((tabId, attachInfo) => {
    var indexOfTab = getIndexOfTab(tabId, openTabs);
    openTabs.splice(indexOfTab, 1);
  });

  chrome.browserAction.onClicked.addListener(function (tab) {
    const width = 500;
    const height = 900;
    const left = screen.width / 2 - width / 2;
    const top = screen.height / 2 - height / 2;
    if (!userLoggedIn) {
      chrome.windows.create(
        {
          url: "../html/auth.html",
          width: width,
          height: height,
          left: left,
          top: top,
          focused: true,
        },
        (window) => {
          currentWindow = window;
        }
      );
    } else {
      const currentTabIndex = getIndexOfTab(tab.id, openTabs);
      if (!openTabs[currentTabIndex].popupOpen) {
        fetch(chrome.runtime.getURL("html/app.html"))
          .then((res) => {
            return res.text();
          })
          .then((data) => {
            const userData = parseJwt(userLoggedIn);
            chrome.windows.getCurrent((w) => {
              chrome.tabs.query(
                {
                  active: true,
                  windowId: w.id,
                },
                function (tabs) {
                  const index = getIndexOfTab(tabs[0].id, openTabs);
                  if (!openTabs[index].popupOpen) {
                    chrome.tabs.sendMessage(openTabs[index].id, {
                      message: "openPopup",
                      payload: data,
                    });
                    chrome.tabs.sendMessage(openTabs[index].id, {
                      message: "userData",
                      payload: userData,
                    });
                    openTabs[index]["popupOpen"] = true;
                  }
                }
              );
            });
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        chrome.windows.getCurrent((w) => {
          chrome.tabs.query(
            {
              active: true,
              currentWindow: true,
            },
            function (tabs) {
              chrome.tabs.sendMessage(tabs[0].id, {
                message: "closePopup",
              });
              openTabs[currentTabIndex].popupOpen = false;
            }
          );
        });
      }
    }
  });

  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.message === "login") {
      flipUserStatus(true, request.payload)
        .then(function (res) {
          if (res.ok) {
            return res.json();
          } else {
            sendResponse({
              message: "error",
            });
          }
        })
        .then(function (data) {
          chrome.storage.local.set({ token: data.token }, function (result) {
            fetch(chrome.runtime.getURL("html/app.html"))
              .then((res) => {
                return res.text();
              })
              .then((htmlData) => {
                if (currentWindow) {
                  chrome.windows.remove(currentWindow.id);
                }
                const userData = parseJwt(data.token);
                userLoggedIn = data.token;
                chrome.windows.getCurrent((w) => {
                  chrome.tabs.query(
                    {
                      active: true,
                      windowId: w.id,
                    },
                    function (tabs) {
                      const tabIndex = getIndexOfTab(tabs[0].id, openTabs);

                      openTabs[tabIndex].popupOpen = true;
                      chrome.tabs.sendMessage(tabs[0].id, {
                        message: "openPopup",
                        payload: htmlData,
                      });
                      chrome.tabs.sendMessage(tabs[0].id, {
                        message: "userData",
                        payload: userData,
                      });
                    }
                  );
                });
                sendResponse({ message: "success" });
              })
              .catch((err) => {
                console.log(err);
              });
          });
        })
        .catch(function (err) {
          console.log(err);
        });
      return true;
    } else if (request.message === "logout") {
    } else if (request.message === "userStatus") {
    }
  });
});

function flipUserStatus(signIn, userInfo) {
  if (signIn) {
    return fetch(`${apiUrl}/api/auth/login`, {
      body: JSON.stringify(userInfo),
      headers: {
        "Content-Type": "application/json",
      },
      method: "post",
    });
  } else if (!signIn) {
    console.log("Log out");
  }
}

function parseJwt(token) {
  var base64Url = token.split(".")[1];
  var base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
  var jsonPayload = decodeURIComponent(
    atob(base64)
      .split("")
      .map(function (c) {
        return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
      })
      .join("")
  );

  return JSON.parse(jsonPayload);
}

function getTabFromOpenTabs(id, tabs) {
  var tabToReturn = undefined;
  tabs.forEach((tab) => {
    if (id == tab.id) {
      tabToReturn = tab;
    }
  });
  return tabToReturn;
}

function getIndexOfTab(id, tabs) {
  var index = 0;
  tabs.forEach((tab) => {
    if (id == tab.id) {
      index = tabs.indexOf(tab);
    }
  });
  return index;
}

  • Don't use the ancient `initEvent`, try the modern CustomEvent, [example](https://stackoverflow.com/a/19312198). Also don't send lots of events but instead send one event with an array that contains all your urls. – wOxxOm Feb 14 '21 at 17:58
  • I made your changes but still having the same issue in youtube, When I emit the custom event the youtube page gets all gray like the default dark theme color, I also tried changing the name of event to make sure its not interfering with youtube, But still having issue –  Feb 14 '21 at 19:51
  • Assuming you reloaded the extension on chrome://extensions page, I guess your real `js/app.js` is doing something wrong. Note that its global variables or functions will override the items defined by the page itself. – wOxxOm Feb 14 '21 at 20:11
  • Oh, I see, it's a completely different problem here: please never do terrible things like `innerHTML += request.payload` – wOxxOm Feb 14 '21 at 20:12

0 Answers0