Options
All
  • Public
  • Public/Protected
  • All
Menu

Module inject

Because extension content scripts run in their own sand-boxed environment they can't easily access the page's Javascript namespace. But this module helps you do exactly that.

You can use injectCode to simply run code in the page's context and evaluateCode if you need to pass a value back.

Using real functions in your code

The code needs to be written in Javascript that can be executed by the browser. It isn't processed in any way. If possible, write an actual function which you then convert to a string to leverage the power of TypeScript.

example

// write the function like you would for any other function, this way it'll
// be compiled to the targeted javascript version
function test(value: any): string {
    return value.toString();
}

const code = `
     // test now holds the compiled test function code
     const test = ${test.toString()};
     return test(5);
`;

// returns "5"
await evaluateCode(code);

Getting something from the page

Let's say you want to access the variable USER_NAME which the page conveniently exposes to the global scope, you can simply grab it using evaluateCode.

example

const username = await evaluateCode(`USER_NAME`);

Running code

If you have to call a function in the page to perform some action, say, changing the colour of the background (called "changeBackgroundColour"), you can use injectCode to simply run it.

example

injectCode(`changeBackgroundColour("green");`);

Index

Type aliases

EvalResultEvent

EvalResultEvent: CustomEvent<EvalResultEventDetails>

Type of an eval result event.

Variables

Const DELETE_AFTER

DELETE_AFTER: string = `(${(() => {const script = document.currentScript;if (script) script.remove();}).toString()})();`

Code mix-in which when executed immediately removes the current script element from the DOM.

see

injectCode with InjectOptions.keepAfterExecution set to false

Const EVAL_TEMPLATE

EVAL_TEMPLATE: string = `${PUSH_RESULT}const run = async () => {{{code}}};run().then(value => pushResult(value, "result")).catch(reason => pushResult(reason, "error"));`

Code mix-in to evaluate some code and expose the return value in the DOM. It relies on PUSH_RESULT.

Requires code, and uid to be set using formatCode.

Works by wrapping code in an async function and pushing the result after finishing.

see

evaluateCode

Const PUSH_RESULT

PUSH_RESULT: string = `const pushResultMarshalError = ${marshalError.toString()};\n`+ `const pushResult = ${((value: any, key: "result" | "error") => {// "sanitise" the data, otherwise `detail` might be nullif (key === "error") {// @ts-ignorevalue = pushResultMarshalError(value);} else if (value)value = JSON.parse(JSON.stringify(value));const event = new CustomEvent("evalresult", {detail: {id: "{{uid}}",[key]: value,},});document.dispatchEvent(event);}).toString()};`

Code mix-in which exposes the pushResult(value: any, key: string) function to "expose" a value in an element so that it can be accessed from the extension context.

Requires the variable uid to be set using formatCode.

see

evaluateCode

Const evalResultEvent$

evalResultEvent$: Observable<CustomEvent<EvalResultEventDetails>> = fromEvent(document, "evalresult") as Observable<EvalResultEvent>

Observable for all eval results

Functions

evaluateCode

  • evaluateCode(code: string): Promise<any>
  • Evaluate code in the context of the page window and return its result. This function can be used to get access to Javascript variables because extensions don't have access to the page's Window object.

    The return value needs to be JSON serializable!

    see

    injectCode if you only need to execute code without getting the result.

    throws

    Any errors that occurred during execution of the code

    Parameters

    • code: string

      Supports both sync and async code. If you don't use an explicit return statement your code will be prefixed with return. This can be used to create simple eval statements:

      // title holds the document title (note: there's no need to use evaluateCode for this)
      const title = await evaluateCode(`document.title`);

    Returns Promise<any>

formatCode

  • formatCode(code: string, args: object): string
  • A simple formatter that can be used to format template code.

    The code uses {{name}} syntax to indicate templates which can be replaced by providing {name: "value"} to the function.

    This function is very basic and shouldn't be used for more complex templates!

    Parameters

    • code: string
    • args: object
      • [key: string]: any

    Returns string

getUid

  • getUid(): string
  • Generate a random id. This function is used to communicate between the windows by giving each evaluation context its own id.

    Returns string

injectCode

  • injectCode(code: string, options?: Partial<InjectOptions>): Element
  • Inject javascript code to be run in the context of the page's Window.

    Parameters

    Returns Element

    script tag that the code was injected to.

Generated using TypeDoc