How to use injectHook method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

content.js

Source: content.js Github

copy
1function injectHook(url, type = '') {
2    const hookScript = document.createElement("script");
3    if (type !== '') hookScript.type = "module";
4    hookScript.src = url;
5    hookScript.onload = function () {
6        this.remove();
7    };
8    (document.head || document.body || document.documentElement).appendChild(hookScript);
9}
10
11
12// injectHook(chrome.extension.getURL('/lib/emoji.js'));
13
14// chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
15//     if (request.message === 'TabUpdated' && document.location.href.includes('https://www.facebook.com/stories')) {
16//         // injectHook(chrome.extension.getURL(`/lib/story.js?v=${getRandom(1, 100)}`), 'module');
17//         // injectHook(chrome.extension.getURL(`/lib/story.js`), 'module');
18//         // chrome.tabs.executeScript(null, {file: 'lib/story.js'});
19//     }
20// })
21
22function getRandom(min, max) {
23    return Math.random() * (max - min) + min;
24}
Full Screen

lifecycle.js

Source: lifecycle.js Github

copy
1import { currentInstance, setCurrentInstance } from "./index";
2import { pauseTracking, resumeTracking } from "./effect";
3import { isArray } from "./utils";
4
5export const LifecycleHooks = {
6  CREATED: "c",
7  MOUNTED: "m",
8  UPDATED: "u"
9};
10
11export function onCreate(fn, app = currentInstance) {
12  injectHook(LifecycleHooks.CREATED, fn, app);
13}
14
15export function onMount(fn, app = currentInstance) {
16  injectHook(LifecycleHooks.MOUNTED, fn, app);
17}
18
19export function onUpdate(fn, app = currentInstance) {
20  injectHook(LifecycleHooks.UPDATED, fn, app);
21}
22
23export function injectHook(type, hook, target) {
24  if (target) {
25    (target[type] || (target[type] = [])).push((...args) => {
26      pauseTracking();
27      setCurrentInstance(target);
28      const res = hook(...args);
29      setCurrentInstance(null);
30      resumeTracking();
31      return res;
32    });
33  }
34}
35
36export function callHook(target, type, ...args) {
37  if (target && isArray(target[type])) {
38    target[type].forEach(hook => {
39      hook(...args);
40    });
41  }
42}
43
44export function callMount(target = currentInstance) {
45  return callHook(target, LifecycleHooks.MOUNTED);
46}
47
48export function callCreate(target = currentInstance) {
49  return callHook(target, LifecycleHooks.CREATED);
50}
51
52export function callUpdate(target = currentInstance) {
53  return callHook(target, LifecycleHooks.UPDATED);
54}
55
Full Screen

lifeCycleHook.js

Source: lifeCycleHook.js Github

copy
1
2function injectHook(type, hook, target = currentInstance, prepend = false) {
3    if (target) {
4        const hooks = target[type] || (target[type] = []);
5        // cache the error handling wrapper for injected hooks so the same hook
6        // can be properly deduped by the scheduler. "__weh" stands for "with error
7        // handling".
8        const wrappedHook = hook.__weh ||
9            (hook.__weh = (...args) => {
10                if (target.isUnmounted) {
11                    return;
12                }
13                // disable tracking inside all lifecycle hooks
14                // since they can potentially be called inside effects.
15                pauseTracking();
16                // Set currentInstance during hook invocation.
17                // This assumes the hook does not synchronously trigger other hooks, which
18                // can only be false when the user does something really funky.
19                setCurrentInstance(target);
20                const res = callWithAsyncErrorHandling(hook, target, type, args);
21                setCurrentInstance(null);
22                resetTracking();
23                return res;
24            });
25        if (prepend) {
26            hooks.unshift(wrappedHook);
27        }
28        else {
29            hooks.push(wrappedHook);
30        }
31        return wrappedHook;
32    }
33    else {
34        const apiName = `on${capitalize(ErrorTypeStrings[type].replace(/ hook$/, ''))}`;
35        warn(`${apiName} is called when there is no active component instance to be ` +
36            `associated with. ` +
37            `Lifecycle injection APIs can only be used during execution of setup().` +
38            ( ` If you are using async setup(), make sure to register lifecycle ` +
39                    `hooks before the first await statement.`
40                ));
41    }
42}
43const createHook = (lifecycle) => (hook, target = currentInstance) => 
44// post-create lifecycle registrations are noops during SSR
45!isInSSRComponentSetup && injectHook(lifecycle, hook, target);
46const onBeforeMount = createHook("bm" /* BEFORE_MOUNT */);
47const onMounted = createHook("m" /* MOUNTED */);
48const onBeforeUpdate = createHook("bu" /* BEFORE_UPDATE */);
49const onUpdated = createHook("u" /* UPDATED */);
50const onBeforeUnmount = createHook("bum" /* BEFORE_UNMOUNT */);
51const onUnmounted = createHook("um" /* UNMOUNTED */);
52const onRenderTriggered = createHook("rtg" /* RENDER_TRIGGERED */);
53const onRenderTracked = createHook("rtc" /* RENDER_TRACKED */);
54const onErrorCaptured = (hook, target = currentInstance) => {
55    injectHook("ec" /* ERROR_CAPTURED */, hook, target);
56};
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)