0

I have a chrome extension in React.js, and I know that it is possible to open the chrome extension immediately after the tab is created (updated), even the page is loading for 4-5 seconds. I have tried to open the extension on "loading" page, but it still opens several seconds after the tab is created (updated).

My code looks something like this (background.js)

//...
chrome.tabs.onActivated.addListener(() => {
  setExtension();
});

chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
  if (changeInfo.status === 'loading') {
    setExtension();
  }
});

And my content.js

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.type === 'INJECT') {
    let modal = document.getElementById('some-modal-id');
    if (!modal) {
      modal = document.createElement('div');
      modal.id = 'some-modal-id';
      modal.innerHTML = `<iframe id="modal-iframe"></iframe>`;
      document.body.appendChild(modal);

      // some more styling code...

      const iframe = document.getElementById('modal-iframe');
      iframe.src = chrome.runtime.getURL('index.html');
    }
    sendResponse({});
  }
  // ...
}

I've tried this piece of advice: wrapping the code that added the iframe to the HTML in setTimeout, but the extension stopped to appear on page loaded at all

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
  if (msg.type === 'INJECT') {
    const timeoutID = setTimeout(() => {
      let modal = document.getElementById('some-modal-id');
      if (!modal) {
        modal = document.createElement('div');
        modal.id = 'some-modal-id';
        modal.innerHTML = `<iframe id="modal-iframe"></iframe>`;
        document.body.appendChild(modal);

        // some more styling code...

        const iframe = document.getElementById('modal-iframe');
        iframe.src = chrome.runtime.getURL('index.html');
      }
      clearTimeout(timeoutID)
      sendResponse({});
    }, 0)
  }
  // ...
}

I've tried to change "run_at" to "document_start" in manifest.json, but it also didn't helped

"content_scripts": [{
    "js": [ "content.js"],
    "css": ["content.css"],
    "matches": [ "<all_urls>"],
    "run_at": "document_start"
  }],
Mrmld Sky
  • 139
  • 1
  • 7
  • Why are you doing it inside onMessage? You can add the iframe immediately at document_start to `document.documentElement` insitead of `document.body`. If it's still slow, you'll have to add the UI right into the page without using an iframe. – wOxxOm Sep 07 '22 at 15:00
  • @wOxxOm thank you, that was the point, it appears immediately even using an iframe. I put the code of creating the elements directly inside content.js. I wanted to ask, if you could put your comment as answer, so I could check it as the solution – Mrmld Sky Sep 08 '22 at 07:59

0 Answers0