Skip to content

Commit

Permalink
feat: add warning when wrong execution context detected
Browse files Browse the repository at this point in the history
  • Loading branch information
prinsss committed Apr 13, 2024
1 parent fc3e336 commit fd58190
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/core/extensions/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,15 @@ import logger from '@/utils/logger';
import { Signal } from '@preact/signals';
import { Extension, ExtensionConstructor, Interceptor } from './extension';

/**
* Global object reference. In some cases, the `unsafeWindow` is not available.
*/
const globalObject = unsafeWindow ?? window ?? globalThis;

/**
* The original XHR method backup.
*/
const xhrOpen = unsafeWindow.XMLHttpRequest.prototype.open;
const xhrOpen = globalObject.XMLHttpRequest.prototype.open;

/**
* The registry for all extensions.
Expand Down Expand Up @@ -105,7 +110,19 @@ export class ExtensionManager {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const manager = this;

unsafeWindow.XMLHttpRequest.prototype.open = function (method: string, url: string) {
// Check for current running context.
// The `window.__SCRIPTS_LOADED__` is injected by the Twitter website.
// See: https://violentmonkey.github.io/posts/inject-into-context/
if (!('__SCRIPTS_LOADED__' in globalObject)) {
logger.error(
'Error: Wrong execution context detected.\n ' +
'This script needs to be injected into "page" context rather than "content" context.\n ' +
'The XMLHttpRequest hook will not work properly.\n ' +
'See: https://github.com/prinsss/twitter-web-exporter/issues/19',
);
}

globalObject.XMLHttpRequest.prototype.open = function (method: string, url: string) {
if (manager.debugEnabled) {
logger.debug(`XHR initialized`, { method, url });
}
Expand Down

0 comments on commit fd58190

Please sign in to comment.