Skip to content

Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.

feat: add `playwright.utils.injectJQuery` (#1337)

Jindřich Bär133de356c4b8
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d0228ad8b..03147b0eb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,7 @@
2.3.1 / TBA
====================
- fix: `utils.apifyClient` early instantiation (#1330)
+- feat: `playwright.injectJQuery()` (#1337)
2.3.0 / 2022/04/07
====================
diff --git a/src/playwright_utils.js b/src/playwright_utils.js
index b829ff538..d521c8984 100644
--- a/src/playwright_utils.js
+++ b/src/playwright_utils.js
@@ -1,14 +1,99 @@
import ow from 'ow';
import _ from 'underscore';
+import { readFile } from 'fs/promises';
import { Page, Response } from 'playwright'; // eslint-disable-line no-unused-vars
+import { LruCache } from '@apify/datastructures';
import log from './utils_log';
import { validators } from './validators';
-/* eslint-disable no-unused-vars,import/named,import/no-duplicates,import/order */
+/* eslint-disable no-unused-vars,import/named */
import { DirectNavigationOptions } from './typedefs';
/* eslint-enable no-unused-vars,import/named,import/no-duplicates,import/order */
-import Request from './request'; // eslint-disable-line import/named,no-unused-vars
+import Request from './request'; // eslint-disable-line no-unused-vars
+
+const jqueryPath = require.resolve('jquery');
+
+const MAX_INJECT_FILE_CACHE_SIZE = 10;
+
+/**
+ * Cache contents of previously injected files to limit file system access.
+ */
+const injectedFilesCache = new LruCache({ maxLength: MAX_INJECT_FILE_CACHE_SIZE });
+
+/**
+ * Injects a JavaScript file into a Playright page.
+ * Unlike Playwright's `addScriptTag` function, this function works on pages
+ * with arbitrary Cross-Origin Resource Sharing (CORS) policies.
+ *
+ * File contents are cached for up to 10 files to limit file system access.
+ *
+ * @param {Page} page
+ * Playwright [`Page`](https://playwright.dev/docs/api/class-page) object.
+ * @param {string} filePath File path
+ * @param {object} [options]
+ * @param {boolean} [options.surviveNavigations]
+ * Enables the injected script to survive page navigations and reloads without need to be re-injected manually.
+ * This does not mean, however, that internal state will be preserved. Just that it will be automatically
+ * re-injected on each navigation before any other scripts get the chance to execute.
+ * @return {Promise<*>}
+ * @memberOf playwright
+ */
+const injectFile = async (page, filePath, options = {}) => {
+ ow(page, ow.object.validate(validators.browserPage));
+ ow(filePath, ow.string);
+ ow(options, ow.object.exactShape({
+ surviveNavigations: ow.optional.boolean,
+ }));
+
+ let contents = injectedFilesCache.get(filePath);
+ if (!contents) {
+ contents = await readFile(filePath, 'utf8');
+ injectedFilesCache.add(filePath, contents);
+ }
+ const evalP = page.evaluate(contents);
+
+ if (options.surviveNavigations) {
+ page.on('framenavigated',
+ () => page.evaluate(contents)
+ .catch((error) => log.warning('An error occured during the script injection!', { error })));
+ }
+
+ return evalP;
+};
+
+/**
+ * Injects the [jQuery](https://jquery.com/) library into a Playwright page.
+ * jQuery is often useful for various web scraping and crawling tasks.
+ * For example, it can help extract text from HTML elements using CSS selectors.
+ *
+ * Beware that the injected jQuery object will be set to the `window.$` variable and thus it might cause conflicts with
+ * other libraries included by the page that use the same variable name (e.g. another version of jQuery).
+ * This can affect functionality of page's scripts.
+ *
+ * The injected jQuery will survive page navigations and reloads.
+ *
+ * **Example usage:**
+ * ```javascript
+ * await Apify.utils.playwright.injectJQuery(page);
+ * const title = await page.evaluate(() => {
+ * return $('head title').text();
+ * });
+ * ```
+ *
+ * Note that `injectJQuery()` does not affect the Playwright
+ * [`page.$()`](https://playwright.dev/docs/api/class-page#page-query-selector)
+ * function in any way.
+ *
+ * @param {Page} page
+ * Playwright [`Page`](https://playwright.dev/docs/api/class-page) object.
+ * @return {Promise<*>}
+ * @memberOf playwright
+ */
+const injectJQuery = (page) => {
+ ow(page, ow.object.validate(validators.browserPage));
+ return injectFile(page, jqueryPath, { surviveNavigations: true });
+};
/**
* Extended version of Playwright's `page.goto()` allowing to perform requests with HTTP method other than GET,
@@ -19,7 +104,7 @@ import Request from './request'; // eslint-disable-line import/named,no-unused-v
* browser cache which degrades performance.
*
* @param {Page} page
- * Puppeteer [`Page`](https://playwright.dev/docs/api/class-page) object.
+ * Playwright [`Page`](https://playwright.dev/docs/api/class-page) object.
* @param {Request} request
* @param {DirectNavigationOptions} [gotoOptions] Custom options for `page.goto()`.
* @return {Promise<(Response|null)>}
@@ -92,4 +177,6 @@ export const gotoExtended = async (page, request, gotoOptions = {}) => {
*/
export const playwrightUtils = {
gotoExtended,
+ injectFile,
+ injectJQuery,
};
diff --git a/src/puppeteer_utils.js b/src/puppeteer_utils.js
index 91f33706a..cf71f65ab 100644
--- a/src/puppeteer_utils.js
+++ b/src/puppeteer_utils.js
@@ -1,7 +1,6 @@
-import fs from 'fs';
+import { readFile } from 'fs/promises';
import ow from 'ow';
import vm from 'vm';
-import util from 'util';
import _ from 'underscore';
import { LruCache } from '@apify/datastructures';
import { Page, Response, DirectNavigationOptions } from 'puppeteer'; // eslint-disable-line no-unused-vars
@@ -14,7 +13,6 @@ import { openKeyValueStore } from './storages/key_value_store';
const jqueryPath = require.resolve('jquery');
const underscorePath = require.resolve('underscore');
-const readFilePromised = util.promisify(fs.readFile);
const MAX_INJECT_FILE_CACHE_SIZE = 10;
const DEFAULT_BLOCK_REQUEST_URL_PATTERNS = ['.css', '.jpg', '.jpeg', '.png', '.svg', '.gif', '.woff', '.pdf', '.zip'];
@@ -61,13 +59,18 @@ const injectFile = async (page, filePath, options = {}) => {
let contents = injectedFilesCache.get(filePath);
if (!contents) {
- contents = await readFilePromised(filePath, 'utf8');
+ contents = await readFile(filePath, 'utf8');
injectedFilesCache.add(filePath, contents);
}
const evalP = page.evaluate(contents);
- return options.surviveNavigations
- ? Promise.all([page.evaluateOnNewDocument(contents), evalP])
- : evalP;
+
+ if (options.surviveNavigations) {
+ page.on('framenavigated',
+ () => page.evaluate(contents)
+ .catch((error) => log.warning('An error occured during the script injection!', { error })));
+ }
+
+ return evalP;
};
/**
diff --git a/test/playwright_utils.test.js b/test/playwright_utils.test.js
index ae03e0172..221a54e6c 100644
--- a/test/playwright_utils.test.js
+++ b/test/playwright_utils.test.js
@@ -1,5 +1,6 @@
import playwright from 'playwright';
import express from 'express';
+import path from 'path';
import Apify from '../build/index';
import LocalStorageDirEmulator from './local_storage_dir_emulator';
import { startExpressAppPromise } from './_helper';
@@ -52,28 +53,122 @@ describe('Apify.utils.playwright', () => {
await localStorageEmulator.destroy();
});
- test('gotoExtended() works', async () => {
- const browser = await playwright.chromium.launch({ headless: true });
-
- try {
- const page = await browser.newPage();
- const request = new Apify.Request({
- url: `http://${HOSTNAME}:${port}/foo`,
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json; charset=utf-8',
- },
- payload: '{ "foo": "bar" }',
- });
-
- const response = await Apify.utils.playwright.gotoExtended(page, request);
-
- const { method, headers, bodyLength } = JSON.parse(await response.text());
- expect(method).toBe('POST');
- expect(bodyLength).toBe(16);
- expect(headers['content-type']).toBe('application/json; charset=utf-8');
- } finally {
- await browser.close();
- }
- }, 60000);
+ describe.each([
+ // ['launchPuppeteer', { launchOptions: { headless: true } }],
+ ['launchPlaywright', { launchOptions: { headless: true } }],
+ ])('with %s', (launchName, launchContext) => {
+ test('injectFile()', async () => {
+ /* eslint-disable no-shadow */
+ const browser = await Apify[launchName](launchContext);
+ const survive = async (browser) => {
+ // Survive navigations
+ const page = await browser.newPage();
+ let result = await page.evaluate(() => window.injectedVariable === 42);
+ expect(result).toBe(false);
+ await Apify.utils.playwright.injectFile(page, path.join(__dirname, 'data', 'inject_file.txt'), { surviveNavigations: true });
+ result = await page.evaluate(() => window.injectedVariable);
+ expect(result).toBe(42);
+ await page.goto('about:chrome');
+ result = await page.evaluate(() => window.injectedVariable);
+ expect(result).toBe(42);
+ await page.goto('https://www.example.com');
+ result = await page.evaluate(() => window.injectedVariable);
+ expect(result).toBe(42);
+ };
+ const remove = async (browser) => {
+ // Remove with navigations
+ const page = await browser.newPage();
+ let result = await page.evaluate(() => window.injectedVariable === 42);
+ expect(result).toBe(false);
+ await page.goto('about:chrome');
+ result = await page.evaluate(() => window.injectedVariable === 42);
+ expect(result).toBe(false);
+ await Apify.utils.playwright.injectFile(page, path.join(__dirname, 'data', 'inject_file.txt'));
+ result = await page.evaluate(() => window.injectedVariable);
+ expect(result).toBe(42);
+ await page.goto('https://www.example.com');
+ result = await page.evaluate(() => window.injectedVariable === 42);
+ expect(result).toBe(false);
+ };
+ try {
+ await Promise.all([survive(browser), remove(browser)]);
+ } finally {
+ await browser.close();
+ }
+ });
+
+ test('injectJQuery()', async () => {
+ const browser = await Apify[launchName](launchContext);
+
+ try {
+ const page = await browser.newPage();
+ await page.goto('about:blank');
+
+ // NOTE: Chrome already defines window.$ as alias to document.querySelector(),
+ // (https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#queryselector)
+ const result1 = await page.evaluate(() => {
+ return {
+ isDefined: window.jQuery !== undefined,
+ };
+ });
+ expect(result1).toEqual({
+ isDefined: false,
+ });
+
+ await Apify.utils.playwright.injectJQuery(page);
+
+ const result2 = await page.evaluate(() => {
+ /* global $ */
+ return {
+ isDefined: window.jQuery === window.$,
+ text: $('h1').text(),
+ };
+ });
+ expect(result2).toEqual({
+ isDefined: true,
+ text: '',
+ });
+
+ await page.reload();
+
+ const result3 = await page.evaluate(() => {
+ return {
+ isDefined: window.jQuery === window.$,
+ text: $('h1').text(),
+ };
+ });
+ expect(result3).toEqual({
+ isDefined: true,
+ text: '',
+ });
+ } finally {
+ await browser.close();
+ }
+ });
+
+ test('gotoExtended() works', async () => {
+ const browser = await playwright.chromium.launch({ headless: true });
+
+ try {
+ const page = await browser.newPage();
+ const request = new Apify.Request({
+ url: `http://${HOSTNAME}:${port}/foo`,
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json; charset=utf-8',
+ },
+ payload: '{ "foo": "bar" }',
+ });
+
+ const response = await Apify.utils.playwright.gotoExtended(page, request);
+
+ const { method, headers, bodyLength } = JSON.parse(await response.text());
+ expect(method).toBe('POST');
+ expect(bodyLength).toBe(16);
+ expect(headers['content-type']).toBe('application/json; charset=utf-8');
+ } finally {
+ await browser.close();
+ }
+ }, 60000);
+ });
});
diff --git a/test/puppeteer_utils.test.js b/test/puppeteer_utils.test.js
index a868b4318..69503c7af 100644
--- a/test/puppeteer_utils.test.js
+++ b/test/puppeteer_utils.test.js
@@ -93,7 +93,7 @@ describe('Apify.utils.puppeteer', () => {
try {
await Promise.all([survive(browser), remove(browser)]);
} finally {
- browser.close();
+ await browser.close();
}
});
@@ -127,8 +127,21 @@ describe('Apify.utils.puppeteer', () => {
isDefined: true,
text: '',
});
+
+ await page.reload();
+
+ const result3 = await page.evaluate(() => {
+ return {
+ isDefined: window.jQuery === window.$,
+ text: $('h1').text(),
+ };
+ });
+ expect(result3).toEqual({
+ isDefined: true,
+ text: '',
+ });
} finally {
- browser.close();
+ await browser.close();
}
});
@@ -151,7 +164,7 @@ describe('Apify.utils.puppeteer', () => {
});
expect(result2).toEqual({ isDefined: true });
} finally {
- browser.close();
+ await browser.close();
}
});
@@ -319,7 +332,7 @@ describe('Apify.utils.puppeteer', () => {
expect(typeof content).toBe('string');
expect(content).toBe('<html><head></head><body></body></html>');
} finally {
- browser.close();
+ await browser.close();
}
});