handlerActiveTab.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import browser from 'webextension-polyfill';
  2. import { sleep } from '@/utils/helper';
  3. import { attachDebugger, injectPreloadScript } from '../helper';
  4. async function activeTab(block) {
  5. try {
  6. const data = {
  7. data: '',
  8. nextBlockId: this.getBlockConnections(block.id),
  9. };
  10. if (this.activeTab.id) {
  11. await browser.tabs.update(this.activeTab.id, { active: true });
  12. return data;
  13. }
  14. const [tab] = await browser.tabs.query({
  15. active: true,
  16. url: '*://*/*',
  17. });
  18. if (!tab?.url.startsWith('http')) {
  19. const error = new Error('invalid-active-tab');
  20. error.data = { url: tab.url };
  21. throw error;
  22. }
  23. this.activeTab = {
  24. ...this.activeTab,
  25. frameId: 0,
  26. id: tab.id,
  27. url: tab.url,
  28. };
  29. this.windowId = tab.windowId;
  30. if (this.settings.debugMode) {
  31. await attachDebugger(tab.id, this.activeTab.id);
  32. this.debugAttached = true;
  33. }
  34. if (this.preloadScripts.length > 0) {
  35. const preloadScripts = this.preloadScripts.map((script) =>
  36. injectPreloadScript({
  37. script,
  38. frameSelector: this.frameSelector,
  39. target: {
  40. tabId: this.activeTab.id,
  41. frameIds: [this.activeTab.frameId || 0],
  42. },
  43. })
  44. );
  45. await Promise.allSettled(preloadScripts);
  46. }
  47. await browser.tabs.update(tab.id, { active: true });
  48. await browser.windows.update(tab.windowId, { focused: true });
  49. await sleep(200);
  50. return data;
  51. } catch (error) {
  52. console.error(error);
  53. error.data = error.data || {};
  54. throw error;
  55. }
  56. }
  57. export default activeTab;