chore: migrate addScriptTag (#8878)

This commit is contained in:
jrandolf 2022-09-01 17:09:57 +02:00 committed by GitHub
parent f57dde1c5b
commit 8f11237a67
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 132 additions and 156 deletions

View File

@ -26,4 +26,4 @@ class Frame {
Promise<[ElementHandle](./puppeteer.elementhandle.md)<HTMLScriptElement>>
a promise that resolves to the added tag when the script's `onload` event fires or when the script content was injected into the frame.
An [element handle](./puppeteer.elementhandle.md) to the injected `<script>` element.

View File

@ -4,7 +4,7 @@ sidebar_label: FrameAddScriptTagOptions.content
# FrameAddScriptTagOptions.content property
Raw JavaScript content to be injected into the frame.
JavaScript to be injected into the frame.
**Signature:**

View File

@ -0,0 +1,15 @@
---
sidebar_label: FrameAddScriptTagOptions.id
---
# FrameAddScriptTagOptions.id property
Sets the `id` of the script.
**Signature:**
```typescript
interface FrameAddScriptTagOptions {
id?: string;
}
```

View File

@ -12,9 +12,10 @@ export interface FrameAddScriptTagOptions
## Properties
| Property | Modifiers | Type | Description |
| ----------------------------------------------------------- | --------- | ------ | ---------------------------------------------------------------------------------------------------------------- |
| [content?](./puppeteer.frameaddscripttagoptions.content.md) | | string | <i>(Optional)</i> Raw JavaScript content to be injected into the frame. |
| [path?](./puppeteer.frameaddscripttagoptions.path.md) | | string | <i>(Optional)</i> The path to a JavaScript file to be injected into the frame. |
| [type?](./puppeteer.frameaddscripttagoptions.type.md) | | string | <i>(Optional)</i> Set the script's <code>type</code>. Use <code>module</code> in order to load an ES2015 module. |
| [url?](./puppeteer.frameaddscripttagoptions.url.md) | | string | <i>(Optional)</i> the URL of the script to be added. |
| Property | Modifiers | Type | Description |
| ----------------------------------------------------------- | --------- | ------ | ---------------------------------------------------------------------------------------------------------------------- |
| [content?](./puppeteer.frameaddscripttagoptions.content.md) | | string | <i>(Optional)</i> JavaScript to be injected into the frame. |
| [id?](./puppeteer.frameaddscripttagoptions.id.md) | | string | <i>(Optional)</i> Sets the <code>id</code> of the script. |
| [path?](./puppeteer.frameaddscripttagoptions.path.md) | | string | <i>(Optional)</i> Path to a JavaScript file to be injected into the frame. |
| [type?](./puppeteer.frameaddscripttagoptions.type.md) | | string | <i>(Optional)</i> Sets the <code>type</code> of the script. Use <code>module</code> in order to load an ES2015 module. |
| [url?](./puppeteer.frameaddscripttagoptions.url.md) | | string | <i>(Optional)</i> URL of the script to be added. |

View File

@ -4,7 +4,7 @@ sidebar_label: FrameAddScriptTagOptions.path
# FrameAddScriptTagOptions.path property
The path to a JavaScript file to be injected into the frame.
Path to a JavaScript file to be injected into the frame.
**Signature:**

View File

@ -4,7 +4,7 @@ sidebar_label: FrameAddScriptTagOptions.type
# FrameAddScriptTagOptions.type property
Set the script's `type`. Use `module` in order to load an ES2015 module.
Sets the `type` of the script. Use `module` in order to load an ES2015 module.
**Signature:**

View File

@ -4,7 +4,7 @@ sidebar_label: FrameAddScriptTagOptions.url
# FrameAddScriptTagOptions.url property
the URL of the script to be added.
URL of the script to be added.
**Signature:**

View File

@ -10,27 +10,23 @@ Adds a `<script>` tag into the page with the desired URL or content.
```typescript
class Page {
addScriptTag(options: {
url?: string;
path?: string;
content?: string;
type?: string;
id?: string;
}): Promise<ElementHandle<HTMLScriptElement>>;
addScriptTag(
options: FrameAddScriptTagOptions
): Promise<ElementHandle<HTMLScriptElement>>;
}
```
## Parameters
| Parameter | Type | Description |
| --------- | ------------------------------------------------------------------------------ | ----------- |
| options | { url?: string; path?: string; content?: string; type?: string; id?: string; } | |
| Parameter | Type | Description |
| --------- | ------------------------------------------------------------------- | ----------------------- |
| options | [FrameAddScriptTagOptions](./puppeteer.frameaddscripttagoptions.md) | Options for the script. |
**Returns:**
Promise&lt;[ElementHandle](./puppeteer.elementhandle.md)&lt;HTMLScriptElement&gt;&gt;
Promise which resolves to the added tag when the script's onload fires or when the script content was injected into frame.
An [element handle](./puppeteer.elementhandle.md) to the injected `<script>` element.
## Remarks

View File

@ -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 the script. Use `module` in order to load an ES2015 module.
*/
type?: string;
/**
* Sets the `id` of the script.
*/
id?: string;
}
/**
@ -736,14 +741,75 @@ export class Frame {
* Adds a `<script>` tag into the page with the desired url or content.
*
* @param options - Options for the script.
* @returns a promise that resolves to the added tag when the script's
* `onload` event fires or when the script content was injected into the
* frame.
* @returns An {@link ElementHandle | element handle} to the injected
* `<script>` element.
*/
async addScriptTag(
options: FrameAddScriptTagOptions
): Promise<ElementHandle<HTMLScriptElement>> {
return this.worlds[MAIN_WORLD].addScriptTag(options);
let {content = '', type} = options;
const {path} = options;
if (+!!options.url + +!!path + +!!content !== 1) {
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 file path in a Node-like environment.'
);
}
throw error;
}
content = await fs.readFile(path, 'utf8');
content += `//# sourceURL=${path.replace(/\n/g, '')}`;
}
type = type ?? 'text/javascript';
return this.worlds[MAIN_WORLD].transferHandle(
await this.worlds[PUPPETEER_WORLD].evaluateHandle(
async ({url, id, type, content}) => {
const script = document.createElement('script');
script.type = type;
script.text = content;
if (url) {
script.src = url;
}
if (id) {
script.id = id;
}
let resolve: undefined | ((value?: unknown) => void);
const promise = new Promise((res, rej) => {
if (url) {
script.addEventListener('load', res, {once: true});
} else {
resolve = res;
}
script.addEventListener(
'error',
event => {
rej(event.message ?? 'Could not load script');
},
{once: true}
);
});
document.head.appendChild(script);
if (resolve) {
resolve();
}
await promise;
return script;
},
{...options, type, content}
)
);
}
/**

View File

@ -117,7 +117,7 @@ export class IsolatedWorld {
#frame: Frame;
#injected: boolean;
#document?: ElementHandle<Document>;
#contextPromise = createDeferredPromise<ExecutionContext>();
#context = createDeferredPromise<ExecutionContext>();
#detached = false;
// Set of bindings that have been registered in the current context.
@ -165,7 +165,7 @@ export class IsolatedWorld {
clearContext(): void {
this.#document = undefined;
this.#contextPromise = createDeferredPromise();
this.#context = createDeferredPromise();
}
setContext(context: ExecutionContext): void {
@ -173,14 +173,14 @@ export class IsolatedWorld {
context.evaluate(injectedSource).catch(debugError);
}
this.#ctxBindings.clear();
this.#contextPromise.resolve(context);
this.#context.resolve(context);
for (const waitTask of this._waitTasks) {
waitTask.rerun();
}
}
hasContext(): boolean {
return this.#contextPromise.resolved();
return this.#context.resolved();
}
_detach(): void {
@ -199,10 +199,10 @@ export class IsolatedWorld {
`Execution context is not available in detached frame "${this.#frame.url()}" (are you trying to evaluate?)`
);
}
if (this.#contextPromise === null) {
if (this.#context === null) {
throw new Error(`Execution content promise is missing`);
}
return this.#contextPromise;
return this.#context;
}
async evaluateHandle<
@ -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.
*

View File

@ -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 {
@ -53,9 +58,9 @@ import {
debugError,
evaluationString,
getExceptionMessage,
importFS,
getReadableAsBuffer,
getReadableFromProtocolStream,
importFS,
isNumber,
isString,
pageBindingDeliverErrorString,
@ -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';
/**
@ -1412,16 +1412,13 @@ export class Page extends EventEmitter {
* Shortcut for
* {@link Frame.addScriptTag | page.mainFrame().addScriptTag(options)}.
*
* @returns Promise which resolves to the added tag when the script's onload
* fires or when the script content was injected into frame.
* @param options - Options for the script.
* @returns An {@link ElementHandle | element handle} to the injected
* `<script>` element.
*/
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);
}

View File

@ -1631,7 +1631,7 @@ describe('Page', function () {
error = error_ as Error;
}
expect(error.message).toBe(
'Provide an object with a `url`, `path` or `content` property'
'Exactly one of `url`, `path`, or `content` may be specified.'
);
});
@ -1702,7 +1702,7 @@ describe('Page', function () {
} catch (error_) {
error = error_ as Error;
}
expect(error.message).toBe('Loading script from /nonexistfile.js failed');
expect(error.message).toContain('Could not load script');
});
it('should work with a path', async () => {
@ -1850,7 +1850,7 @@ describe('Page', function () {
path: path.join(__dirname, '../assets/injectedstyle.css'),
});
const styleHandle = (await page.$('style'))!;
const styleContent = await page.evaluate((style: HTMLStyleElement) => {
const styleContent = await page.evaluate(style => {
return style.innerHTML;
}, styleHandle);
expect(styleContent).toContain(path.join('assets', 'injectedstyle.css'));