Skip to content

Commit

Permalink
chore: migrate addScriptTag handler
Browse files Browse the repository at this point in the history
  • Loading branch information
jrandolf committed Sep 1, 2022
1 parent 3bbb518 commit c1279b0
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 120 deletions.
68 changes: 63 additions & 5 deletions src/common/Frame.ts
Expand Up @@ -49,24 +49,29 @@ export interface FrameWaitForFunctionOptions {
*/
export interface FrameAddScriptTagOptions {
/**
* the URL of the script to be added.
* URL of the script to be added.
*/
url?: string;
/**
* The path to a JavaScript file to be injected into the frame.
* Path to a JavaScript file to be injected into the frame.
*
* @remarks
* If `path` is a relative path, it is resolved relative to the current
* working directory (`process.cwd()` in Node.js).
*/
path?: string;
/**
* Raw JavaScript content to be injected into the frame.
* JavaScript to be injected into the frame.
*/
content?: string;
/**
* Set the script's `type`. Use `module` in order to load an ES2015 module.
* Sets the `type` of thescript. Use `module` in order to load an ES2015 module.
*/
type?: string;
/**
* Sets the `id` of the script.
*/
id?: string;
}

/**
Expand Down Expand Up @@ -743,7 +748,60 @@ export class Frame {
async addScriptTag(
options: FrameAddScriptTagOptions
): Promise<ElementHandle<HTMLScriptElement>> {
return this.worlds[MAIN_WORLD].addScriptTag(options);
let {content} = options;
const {path} = options;
if (options.url && path && content) {
throw new Error(
'Exactly one of `url`, `path`, or `content` may be specified.'
);
}
if (path) {
let fs;
try {
fs = (await import('fs')).promises;
} catch (error) {
if (error instanceof TypeError) {
throw new Error(
'Can only pass a filepath to addScriptTag in a Node-like environment.'
);
}
throw error;
}
content = await fs.readFile(path, 'utf8');
content += `//# sourceURL=${path.replace(/\n/g, '')}`;
options.content = content;
}

return this.worlds[PUPPETEER_WORLD].evaluateHandle(
async ({
url,
id,
type,
content,
}: Omit<FrameAddScriptTagOptions, 'path'>) => {
const script = document.createElement('script');
if (url) {
script.src = url;
}
if (id) {
script.id = id;
}
if (type) {
script.type = type;
}
if (content) {
script.text = content;
}
const promise = new Promise((res, rej) => {
script.onload = res;
script.onerror = rej;
});
document.head.appendChild(script);
await promise;
return script;
},
options
);
}

/**
Expand Down
99 changes: 0 additions & 99 deletions src/common/IsolatedWorld.ts
Expand Up @@ -334,105 +334,6 @@ export class IsolatedWorld {
}
}

/**
* Adds a script tag into the current context.
*
* @remarks
* You can pass a URL, filepath or string of contents. Note that when running Puppeteer
* in a browser environment you cannot pass a filepath and should use either
* `url` or `content`.
*/
async addScriptTag(options: {
url?: string;
path?: string;
content?: string;
id?: string;
type?: string;
}): Promise<ElementHandle<HTMLScriptElement>> {
const {
url = null,
path = null,
content = null,
id = '',
type = '',
} = options;
if (url !== null) {
try {
const context = await this.executionContext();
return await context.evaluateHandle(addScriptUrl, url, id, type);
} catch (error) {
throw new Error(`Loading script from ${url} failed`);
}
}

if (path !== null) {
let fs;
try {
fs = (await import('fs')).promises;
} catch (error) {
if (error instanceof TypeError) {
throw new Error(
'Can only pass a filepath to addScriptTag in a Node-like environment.'
);
}
throw error;
}
let contents = await fs.readFile(path, 'utf8');
contents += '//# sourceURL=' + path.replace(/\n/g, '');
const context = await this.executionContext();
return await context.evaluateHandle(addScriptContent, contents, id, type);
}

if (content !== null) {
const context = await this.executionContext();
return await context.evaluateHandle(addScriptContent, content, id, type);
}

throw new Error(
'Provide an object with a `url`, `path` or `content` property'
);

async function addScriptUrl(url: string, id: string, type: string) {
const script = document.createElement('script');
script.src = url;
if (id) {
script.id = id;
}
if (type) {
script.type = type;
}
const promise = new Promise((res, rej) => {
script.onload = res;
script.onerror = rej;
});
document.head.appendChild(script);
await promise;
return script;
}

function addScriptContent(
content: string,
id: string,
type = 'text/javascript'
) {
const script = document.createElement('script');
script.type = type;
script.text = content;
if (id) {
script.id = id;
}
let error = null;
script.onerror = e => {
return (error = e);
};
document.head.appendChild(script);
if (error) {
throw error;
}
return script;
}
}

/**
* Adds a style tag into the current context.
*
Expand Down
28 changes: 12 additions & 16 deletions src/common/Page.ts
Expand Up @@ -16,23 +16,28 @@

import {Protocol} from 'devtools-protocol';
import type {Readable} from 'stream';
import {Accessibility} from './Accessibility.js';
import {assert} from '../util/assert.js';
import {
createDeferredPromise,
DeferredPromise,
} from '../util/DeferredPromise.js';
import {isErrorLike} from '../util/ErrorLike.js';
import {Accessibility} from './Accessibility.js';
import {Browser, BrowserContext} from './Browser.js';
import {CDPSession, CDPSessionEmittedEvents} from './Connection.js';
import {ConsoleMessage, ConsoleMessageType} from './ConsoleMessage.js';
import {Coverage} from './Coverage.js';
import {Dialog} from './Dialog.js';
import {MAIN_WORLD, WaitForSelectorOptions} from './IsolatedWorld.js';
import {ElementHandle} from './ElementHandle.js';
import {EmulationManager} from './EmulationManager.js';
import {EventEmitter, Handler} from './EventEmitter.js';
import {FileChooser} from './FileChooser.js';
import {Frame, FrameAddScriptTagOptions} from './Frame.js';
import {FrameManager, FrameManagerEmittedEvents} from './FrameManager.js';
import {Frame} from './Frame.js';
import {HTTPRequest} from './HTTPRequest.js';
import {HTTPResponse} from './HTTPResponse.js';
import {Keyboard, Mouse, MouseButton, Touchscreen} from './Input.js';
import {MAIN_WORLD, WaitForSelectorOptions} from './IsolatedWorld.js';
import {JSHandle} from './JSHandle.js';
import {PuppeteerLifeCycleEvent} from './LifecycleWatcher.js';
import {
Expand All @@ -53,9 +58,9 @@ import {
debugError,
evaluationString,
getExceptionMessage,
importFS,
getReadableAsBuffer,
getReadableFromProtocolStream,
importFS,
isNumber,
isString,
pageBindingDeliverErrorString,
Expand All @@ -67,11 +72,6 @@ import {
waitForEvent,
waitWithTimeout,
} from './util.js';
import {isErrorLike} from '../util/ErrorLike.js';
import {
createDeferredPromise,
DeferredPromise,
} from '../util/DeferredPromise.js';
import {WebWorker} from './WebWorker.js';

/**
Expand Down Expand Up @@ -1415,13 +1415,9 @@ export class Page extends EventEmitter {
* @returns Promise which resolves to the added tag when the script's onload
* fires or when the script content was injected into frame.
*/
async addScriptTag(options: {
url?: string;
path?: string;
content?: string;
type?: string;
id?: string;
}): Promise<ElementHandle<HTMLScriptElement>> {
async addScriptTag(
options: FrameAddScriptTagOptions
): Promise<ElementHandle<HTMLScriptElement>> {
return this.mainFrame().addScriptTag(options);
}

Expand Down

0 comments on commit c1279b0

Please sign in to comment.