handlerNewTab.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import browser from 'webextension-polyfill';
  2. import { isWhitespace, sleep } from '@/utils/helper';
  3. import { waitTabLoaded, attachDebugger, sendDebugCommand } from '../helper';
  4. async function newTab({ id, data }) {
  5. if (this.windowId) {
  6. try {
  7. await browser.windows.get(this.windowId);
  8. } catch (error) {
  9. this.windowId = null;
  10. }
  11. }
  12. const isInvalidUrl = !/^https?/.test(data.url);
  13. if (isInvalidUrl) {
  14. const error = new Error(
  15. isWhitespace(data.url) ? 'url-empty' : 'invalid-active-tab'
  16. );
  17. error.data = { url: data.url };
  18. throw error;
  19. }
  20. let tab = null;
  21. const isChrome = BROWSER_TYPE === 'chrome';
  22. if (data.updatePrevTab && this.activeTab.id) {
  23. tab = await browser.tabs.update(this.activeTab.id, {
  24. url: data.url,
  25. active: data.active,
  26. });
  27. } else {
  28. tab = await browser.tabs.create({
  29. url: data.url,
  30. active: data.active,
  31. windowId: this.windowId,
  32. });
  33. }
  34. this.activeTab.url = data.url;
  35. if (tab) {
  36. if (this.settings.debugMode || data.customUserAgent) {
  37. await attachDebugger(tab.id, this.activeTab.id);
  38. this.debugAttached = true;
  39. if (data.customUserAgent && isChrome) {
  40. await sendDebugCommand(tab.id, 'Network.setUserAgentOverride', {
  41. userAgent: data.userAgent,
  42. });
  43. await browser.tabs.reload(tab.id);
  44. await sleep(1000);
  45. }
  46. }
  47. this.activeTab.id = tab.id;
  48. this.windowId = tab.windowId;
  49. }
  50. if (data.inGroup && !data.updatePrevTab) {
  51. const options = {
  52. groupId: this.activeTab.groupId,
  53. tabIds: this.activeTab.id,
  54. };
  55. if (!this.activeTab.groupId) {
  56. options.createProperties = {
  57. windowId: this.windowId,
  58. };
  59. }
  60. if (isChrome) {
  61. chrome.tabs.group(options, (tabGroupId) => {
  62. this.activeTab.groupId = tabGroupId;
  63. });
  64. }
  65. }
  66. this.activeTab.frameId = 0;
  67. if (isChrome && !this.settings.debugMode && data.customUserAgent) {
  68. chrome.debugger.detach({ tabId: tab.id });
  69. }
  70. if (this.preloadScripts.length > 0) {
  71. const preloadScripts = this.preloadScripts.map((script) =>
  72. this._sendMessageToTab(script)
  73. );
  74. await Promise.allSettled(preloadScripts);
  75. }
  76. if (data.waitTabLoaded) {
  77. await waitTabLoaded({
  78. listenError: true,
  79. tabId: this.activeTab.id,
  80. ms: this.settings?.tabLoadTimeout ?? 30000,
  81. });
  82. }
  83. return {
  84. data: data.url,
  85. nextBlockId: this.getBlockConnections(id),
  86. };
  87. }
  88. export default newTab;