execute-content-script.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import browser from 'webextension-polyfill';
  2. export async function getFrames(tabId) {
  3. try {
  4. const frames = await browser.webNavigation.getAllFrames({ tabId });
  5. const framesObj = frames.reduce((acc, { frameId, url }) => {
  6. const key = url === 'about:blank' ? '' : url;
  7. acc[key] = frameId;
  8. return acc;
  9. }, {});
  10. return framesObj;
  11. } catch (error) {
  12. console.error(error);
  13. return {};
  14. }
  15. }
  16. async function contentScriptExist(tabId, frameId = 0) {
  17. try {
  18. await browser.tabs.sendMessage(
  19. tabId,
  20. { type: 'content-script-exists' },
  21. { frameId }
  22. );
  23. return true;
  24. } catch (error) {
  25. return false;
  26. }
  27. }
  28. export default async function (tabId, frameId = 0) {
  29. try {
  30. const currentFrameId = typeof frameId !== 'number' ? 0 : frameId;
  31. const isScriptExists = await contentScriptExist(tabId, currentFrameId);
  32. if (!isScriptExists) {
  33. await browser.tabs.executeScript(tabId, {
  34. runAt: 'document_end',
  35. frameId: currentFrameId,
  36. file: './contentScript.bundle.js',
  37. });
  38. }
  39. } catch (error) {
  40. console.error(error);
  41. throw error;
  42. }
  43. }