# JavaScript Interop

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: Browser Integration
Source: https://www.devtutorials.ai/learn/blazor/browser-integration/javascript-interop

> JavaScript interop in Blazor: when to use it, adding JavaScript files, IJSRuntime with InvokeAsync and InvokeVoidAsync, arguments and return values, sync calls, modules, interop timing, [JSInvokable] and DotNetObjectReference, JSException and disposing references.

## JavaScript Interop Overview

- **JavaScript** is the language every browser runs. Most websites use it for things like copying text or saving data in the browser.
- **Interop** (short for *interoperability*) means two languages working together.
- **JavaScript interop** (JS interop) lets your C# code call JavaScript functions, and lets JavaScript call your C# methods.
- Blazor does most work in C#. JS interop is the door to browser features that only JavaScript can reach.

**Real-World Example:**

- Ravi wants a **Copy coupon** button that puts "TEA10" on the customer's clipboard.
- He also wants the shop to remember the customer's name in the browser.
- Both are browser features. His C# calls a small JavaScript function for each one.

<figure className="blz-fig">
<svg viewBox="0 0 640 180" role="img" aria-labelledby="fig-js-bridge">
  <title id="fig-js-bridge">Animation: two islands, C# with Blazor on the left and JavaScript with the browser on the right, joined by a bridge called JS interop. A dot crosses from C# to JavaScript carrying greet("Asha"), then a dot comes back carrying "Hello, Asha".</title>
  <defs><marker id="fig-js-bridge-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="pur" x="20" y="40" width="200" height="110" rx="12" />
  <text className="t m" x="120" y="70" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>C# (Blazor)</text>
  <text className="t" x="120" y="100" textAnchor="middle" style={{ fontSize: 11 }}>your components</text>
  <rect className="org" x="420" y="40" width="200" height="110" rx="12" />
  <text className="t m" x="520" y="70" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>JavaScript</text>
  <text className="t" x="520" y="100" textAnchor="middle" style={{ fontSize: 11 }}>clipboard, storage...</text>
  <rect className="box" x="220" y="80" width="200" height="30" rx="6" />
  <text className="t m" x="320" y="100" textAnchor="middle" style={{ fontSize: 12 }}>JS interop bridge</text>
  <text className="t" x="320" y="66" textAnchor="middle" style={{ fontSize: 11 }}>greet("Asha") →<animate attributeName="opacity" values="1;1;0;0" keyTimes="0;0.45;0.5;1" dur="5s" repeatCount="indefinite" /></text>
  <text className="t" x="320" y="135" textAnchor="middle" style={{ fontSize: 11 }} opacity="0">← "Hello, Asha"<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.5;0.55;1" dur="5s" repeatCount="indefinite" /></text>
  <circle r="7" cy="95" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="220;420;420;220;220" keyTimes="0;0.45;0.5;0.95;1" dur="5s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>JS interop is a bridge: C# calls JavaScript, and the answer comes back.</figcaption>
</figure>

## When to Use JS Interop

- **Use it** for browser features that Blazor does not have, like the clipboard, `localStorage` or the page's scroll position.
- **Use it** to reuse a JavaScript library, like a chart or a map.
- **Do not use it** for things Blazor already does: showing and hiding, clicks, `@bind` and changing text. Plain C# is simpler there.

<div className="tscroll">

| Task | JS interop? |
|---|---|
| Copy text to the clipboard | Yes |
| Save a value in `localStorage` | Yes |
| Draw a chart with a JS library | Yes |
| Show a message when a button is clicked | No, use `@onclick` |
| Hide a panel | No, use `@if` |

</div>

Blazor owns the HTML it renders. Do not let JavaScript change those elements, or Blazor and JavaScript will fight over them.

## Adding JavaScript Files

- JavaScript files go in the `wwwroot` folder, for example `wwwroot/js/tea.js`. Files in `wwwroot` are sent to the browser as they are.
- Load the file in `Components/App.razor`, **after** Blazor's own script, with a `<script>` tag.
- Put your functions on one object, like `window.teaShop`. Then C# can call them by name, like `teaShop.greet`.

      <script src="@Assets["_framework/blazor.web.js"]"></script>
      <script src="js/tea.js"></script>
</body>
`}
/>

A component can also have its own JavaScript file next to it, like `Order.razor.js`. It is loaded as a **module**. You learn modules below.

## Calling JavaScript from C#

### IJSRuntime

- `IJSRuntime` is Blazor's **service** for calling JavaScript. A **service** is a ready-made helper that Blazor gives you.
- Get it with `@inject IJSRuntime JS` at the top of the component.
- Then call a function by its name: `JS.InvokeAsync<string>("teaShop.greet", "Asha")`.

In the below example, `tea.js` defines `teaShop.greet`. The button in `Home.razor` calls it and shows the answer.

<p>@message</p>

@code {
      private string message = "";

      private async Task SayHello()
      {
          message = await JS.InvokeAsync<string>("teaShop.greet", "Asha");
      }
}
`,
    "wwwroot/js/tea.js": `window.teaShop = {
      greet: function (name) {
          return "Hello, " + name + "!";
      }
};
`,
  }}
/>

### Async Calls (InvokeAsync, InvokeVoidAsync)

- **Async** means "do not wait and freeze the page". The call finishes later, and `await` waits for it without blocking.
- `InvokeAsync<T>` calls a function and **gets a value back** of type `T`.
- `InvokeVoidAsync` calls a function that returns **nothing**, like "save this".

In the below example, **Save** uses `InvokeVoidAsync` to store the name in `localStorage`. **Load** uses `InvokeAsync<string>` to read it back.

<button @onclick="Save">Save</button>
<button @onclick="Load">Load</button>
<p>Saved name: @saved</p>

@code {
      private string name = "Asha";
      private string saved = "";

      private async Task Save() =>
          await JS.InvokeVoidAsync("teaShop.saveName", name);

      private async Task Load() =>
          saved = await JS.InvokeAsync<string>("teaShop.loadName") ?? "";
}
`,
    "wwwroot/js/tea.js": `window.teaShop = {
      saveName: function (name) {
          localStorage.setItem("teaName", name);
      },
      loadName: function () {
          return localStorage.getItem("teaName");
      }
};
`,
  }}
/>

### Passing Arguments and Return Values

- You can pass numbers, strings, lists and objects. Blazor turns them into **JSON**: a text format that both C# and JavaScript understand.
- A returned JavaScript object becomes a C# object when the property names match (upper or lower case does not matter).

In the below example, C# passes cups and price to `teaShop.bill`. JavaScript returns an object with `total` and `message`, and C# reads it as a `Bill` record.

<p>@bill?.Message</p>
<p>Total: ₹@bill?.Total</p>

@code {
      private Bill? bill;

      private async Task GetBill() =>
          bill = await JS.InvokeAsync<Bill>("teaShop.bill", 3, 20);

      private record Bill(int Total, string Message);
}
`,
    "wwwroot/js/tea.js": `window.teaShop = {
      bill: function (cups, price) {
          return {
              total: cups * price,
              message: cups + " cups of tea"
          };
      }
};
`,
  }}
/>

### Sync Calls (IJSInProcessRuntime)

- **Sync** means the call finishes **right away**, with no `await`.
- In Interactive **WebAssembly**, C# and JavaScript run in the same browser, so a sync call is possible.
- Cast `JS` to `IJSInProcessRuntime` and use `Invoke<T>`. It does **not** work in Interactive Server, where JavaScript is far away in the browser.

In the below example, `Invoke<int>` gets the window width at once, with no `await`.

<p>@text</p>

@code {
      private string text = "";

      private void ReadWidth()
      {
          var sync = (IJSInProcessRuntime)JS;
          int width = sync.Invoke<int>("teaShop.windowWidth");
          text = $"The window is {width} pixels wide.";
      }
}
`,
    "wwwroot/js/tea.js": `window.teaShop = {
      windowWidth: function () {
          return window.innerWidth;
      }
};
`,
  }}
/>

### JavaScript Modules (IJSObjectReference)

- A **module** is a JavaScript file that **exports** its functions with `export`. Nothing is added to `window`, so names do not clash.
- C# loads a module with `JS.InvokeAsync<IJSObjectReference>("import", "./js/discount.js")`.
- `IJSObjectReference` is a **reference**: a handle that points to the loaded module. Call its functions through it.
- No `<script>` tag is needed in `App.razor` for a module.

In the below example, `Home.razor` imports `discount.js` once, in `OnAfterRenderAsync`, and calls its `discount` function.

<p>Price: ₹@price</p>

@code {
      private IJSObjectReference? module;
      private int price = 100;

      protected override async Task OnAfterRenderAsync(bool firstRender)
      {
          if (firstRender)
              module = await JS.InvokeAsync<IJSObjectReference>("import", "./js/discount.js");
      }

      private async Task Apply()
      {
          if (module != null)
              price = await module.InvokeAsync<int>("discount", price, 10);
      }

      public async ValueTask DisposeAsync()
      {
          if (module != null) await module.DisposeAsync();
      }
}
`,
    "wwwroot/js/discount.js": `export function discount(price, percent) {
      return price - price * percent / 100;
}
`,
  }}
/>

### Interop Timing (OnAfterRenderAsync)

- During **prerendering** (see **Server Rendering**), there is no browser yet, so JavaScript cannot run.
- Also, an element exists in the browser only **after** the component renders.
- So call JavaScript in `OnAfterRenderAsync`, usually only when `firstRender` is `true`. Not in `OnInitialized`.
- `@ref` stores an element in a C# field of type `ElementReference`, so you can pass it to JavaScript.

<figure className="blz-fig">
<svg viewBox="0 0 640 130" role="img" aria-labelledby="fig-js-timing">
  <title id="fig-js-timing">Animation along a timeline: OnInitialized, then Render, then OnAfterRenderAsync. A red cross on OnInitialized says too early: no element yet. A green tick on OnAfterRenderAsync says the element exists: call JavaScript here.</title>
  <defs><marker id="fig-js-timing-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="box" x="20" y="60" width="170" height="50" rx="10" />
  <text className="t m" x="105" y="90" textAnchor="middle" style={{ fontSize: 12 }}>OnInitialized</text>
  <rect className="org" x="235" y="60" width="170" height="50" rx="10" />
  <text className="t m" x="320" y="90" textAnchor="middle" style={{ fontSize: 12 }}>Render</text>
  <rect className="grn" x="450" y="60" width="170" height="50" rx="10" />
  <text className="t m" x="535" y="90" textAnchor="middle" style={{ fontSize: 12 }}>OnAfterRenderAsync</text>
  <path className="line" d="M190 85 H231" markerEnd="url(#fig-js-timing-a)" />
  <path className="line" d="M405 85 H446" markerEnd="url(#fig-js-timing-a)" />
  <text className="t" x="105" y="40" textAnchor="middle" style={{ fontSize: 12, fill: "#dc2626" }}>✗ too early: no element</text>
  <text className="t" x="535" y="40" textAnchor="middle" style={{ fontSize: 12, fill: "#16a34a" }}>✓ call JavaScript here</text>
  <circle r="7" cy="85" style={{ fill: "#7c3aed" }}>
    <animate attributeName="cx" values="105;320;535;535" keyTimes="0;0.4;0.8;1" dur="4s" repeatCount="indefinite" />
  </circle>
</svg>
<figcaption>Call JavaScript after the render, when the elements exist in the browser.</figcaption>
</figure>

In the below example, `@ref` stores the name box in `nameBox`. In `OnAfterRenderAsync`, `teaShop.focus` puts the cursor in it.

<p>@status</p>

@code {
      private ElementReference nameBox;
      private string status = "Waiting for the first render...";

      protected override async Task OnAfterRenderAsync(bool firstRender)
      {
          if (firstRender)
          {
              await JS.InvokeVoidAsync("teaShop.focus", nameBox);
              status = "The name box has the cursor.";
              StateHasChanged();
          }
      }
}
`,
    "wwwroot/js/tea.js": `window.teaShop = {
      focus: function (element) {
          element.focus();
      }
};
`,
  }}
/>

- For focus only, Blazor also has a shortcut with no JavaScript: `await nameBox.FocusAsync();`.

## Calling C# from JavaScript

- Sometimes JavaScript must tell C# something, for example when a JavaScript timer or library finishes.
- Mark the C# method with `[JSInvokable]`, so JavaScript is allowed to call it.

### Static Methods ([JSInvokable])

- A **static** method belongs to the class, not to one component. It cannot change the fields of a component on the page.
- JavaScript calls it with `DotNet.invokeMethodAsync("AssemblyName", "MethodName")`.
- The **assembly name** is your project's name, like `"TeaShop"`. In the code box it changes on every Run, so C# passes it to JavaScript.

In the below example, JavaScript asks the static C# method `GetSpecial` for today's special.

<p>@answer</p>

@code {
      private string answer = "";

      [JSInvokable]
      public static string GetSpecial() => "Masala Tea";

      private async Task Ask()
      {
          // In your own app, JavaScript can use your project name directly.
          string assembly = typeof(Home).Assembly.GetName().Name!;
          answer = await JS.InvokeAsync<string>("teaShop.askSpecial", assembly);
      }
}
`,
    "wwwroot/js/tea.js": `window.teaShop = {
      askSpecial: async function (assembly) {
          const special = await DotNet.invokeMethodAsync(assembly, "GetSpecial");
          return "JavaScript asked C#: today's special is " + special;
      }
};
`,
  }}
/>

### Instance Methods (DotNetObjectReference)

- An **instance** method belongs to one component on the page, so it can change its fields.
- `DotNetObjectReference.Create(this)` makes a reference to the component. Pass it to JavaScript.
- JavaScript calls `reference.invokeMethodAsync("MethodName")`. In C#, the method has `[JSInvokable]` and calls `StateHasChanged()` to update the page.

In the below example, JavaScript starts a 2-second tea timer. When it ends, it calls `TeaReady` on this component.

<p>@status</p>

@code {
      private string status = "Click to start the timer.";
      private DotNetObjectReference<Home>? self;

      private async Task Start()
      {
          self ??= DotNetObjectReference.Create(this);
          status = "Brewing...";
          await JS.InvokeVoidAsync("teaShop.startTimer", self, 2000);
      }

      [JSInvokable]
      public void TeaReady()
      {
          status = "Your tea is ready!";
          StateHasChanged();
      }

      public void Dispose() => self?.Dispose();
}
`,
    "wwwroot/js/tea.js": `window.teaShop = {
      startTimer: function (dotnet, ms) {
          setTimeout(function () {
              dotnet.invokeMethodAsync("TeaReady");
          }, ms);
      }
};
`,
  }}
/>

<figure className="blz-fig">
<svg viewBox="0 0 640 180" role="img" aria-labelledby="fig-js-ref">
  <title id="fig-js-ref">Animation: C# passes a reference card labelled Home component to JavaScript. Two seconds later, JavaScript uses the card to call TeaReady back on the same component, which shows Your tea is ready.</title>
  <defs><marker id="fig-js-ref-a" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="pur" x="20" y="40" width="200" height="110" rx="12" />
  <text className="t m" x="120" y="66" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Home component</text>
  <text className="t" x="120" y="100" textAnchor="middle" style={{ fontSize: 11 }}>Brewing...<animate attributeName="opacity" values="1;1;0;0" keyTimes="0;0.75;0.8;1" dur="5s" repeatCount="indefinite" /></text>
  <text className="t" x="120" y="100" textAnchor="middle" style={{ fontSize: 11 }} opacity="0">Your tea is ready!<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.75;0.8;1" dur="5s" repeatCount="indefinite" /></text>
  <rect className="org" x="420" y="40" width="200" height="110" rx="12" />
  <text className="t m" x="520" y="66" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>JavaScript</text>
  <text className="t" x="520" y="100" textAnchor="middle" style={{ fontSize: 11 }}>setTimeout(2000)</text>
  <text className="t" x="320" y="70" textAnchor="middle" style={{ fontSize: 11 }}>reference →</text>
  <text className="t" x="320" y="135" textAnchor="middle" style={{ fontSize: 11 }}>← TeaReady()</text>
  <rect x="0" y="0" width="34" height="22" rx="4" style={{ fill: "#ede9fe", stroke: "#7c3aed" }}>
    <animate attributeName="x" values="220;400;400;400;220;220" keyTimes="0;0.3;0.35;0.55;0.75;1" dur="5s" repeatCount="indefinite" />
    <animate attributeName="y" values="80;80;80;115;115;115" keyTimes="0;0.3;0.35;0.55;0.75;1" dur="5s" repeatCount="indefinite" />
  </rect>
</svg>
<figcaption>JavaScript keeps the reference and uses it to call the same component back.</figcaption>
</figure>

## Practical Uses

Common jobs for JS interop in a Blazor app:

- **Clipboard:** copy a coupon code with `navigator.clipboard.writeText`.
- **Browser storage:** remember values with `localStorage`.
- **Scrolling:** jump to the top of a long page with `window.scrollTo`.
- **Libraries:** draw charts or maps with a JavaScript library.

In the below example, **Copy coupon** puts "TEA10" on your clipboard. Paste it anywhere to check.

<button @onclick="Copy">Copy coupon</button>
<p>@status</p>

@code {
      private string status = "";

      private async Task Copy()
      {
          bool ok = await JS.InvokeAsync<bool>("teaShop.copy", "TEA10");
          status = ok ? "Copied! Paste it at checkout." : "Copy is not allowed here.";
      }
}
`,
    "wwwroot/js/tea.js": `window.teaShop = {
      copy: async function (text) {
          try {
              await navigator.clipboard.writeText(text);
              return true;
          } catch {
              return false;
          }
      }
};
`,
  }}
/>

## Interop Errors (JSException)

- If the JavaScript function does not exist, or it throws an error, C# gets a `JSException`.
- An **exception** is how C# reports an error. Without handling it, the component breaks.
- Catch it with `try` and `catch (JSException ex)`, and show a friendly message.

In the below example, `teaShop.print` does not exist. The `catch` block shows a friendly message instead of breaking the page.

<p>@status</p>

@code {
      private string status = "";

      private async Task Print()
      {
          try
          {
              await JS.InvokeVoidAsync("teaShop.print");
              status = "Printed.";
          }
          catch (JSException)
          {
              status = "Sorry, printing is not available.";
          }
      }
}
`,
  }}
/>

In Interactive Server, a call can also fail with `JSDisconnectedException` when the user has closed the tab. You can safely ignore it in `Dispose`.

## Disposing JS References

- **Disposing** means releasing something you no longer need, so it does not keep using memory.
- An `IJSObjectReference` (a module) keeps JavaScript memory. Call `await module.DisposeAsync()`.
- A `DotNetObjectReference` keeps your component alive for JavaScript. Call `self.Dispose()`.
- Do both when the component is removed: use `@implements IAsyncDisposable` or `IDisposable`, as you learned in **Component Lifecycle**.

- The module and instance examples above already dispose their references this way.

## Common mistakes

<div className="tscroll">

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| Calling JavaScript in `OnInitialized` | The browser is ready at once | Call it in `OnAfterRenderAsync` with `firstRender` | An error during prerendering |
| Changing Blazor's elements with JavaScript | Both can edit the same HTML | Let Blazor own its HTML. Use JS only for browser features | The page shows wrong or broken content |
| `InvokeAsync` without a type for a function that returns nothing | Every call needs a return type | Use `InvokeVoidAsync` | A build error or a wrong value |
| Using `IJSInProcessRuntime` in Interactive Server | Sync calls work everywhere | Use it only in WebAssembly | An error: the cast fails |
| A C# method called from JS without `[JSInvokable]` | Any public method can be called | Add `[JSInvokable]` | JavaScript gets an error |
| Never disposing a `DotNetObjectReference` | Blazor cleans it up | Dispose it in `Dispose` | The component stays in memory |

</div>

## Check Yourself

## Exercises

## What to Remember

- JS interop lets C# call JavaScript and JavaScript call C#. Use it only for browser features and JS libraries.
- Put JavaScript in `wwwroot/js` and load it in `App.razor` after `blazor.web.js`. Modules need no script tag.
- `@inject IJSRuntime JS`, then `InvokeAsync<T>` for a value or `InvokeVoidAsync` for no value. Arguments and results travel as JSON.
- `IJSInProcessRuntime.Invoke<T>` is a sync call, for WebAssembly only.
- Load a module with `InvokeAsync<IJSObjectReference>("import", path)`.
- Call JavaScript in `OnAfterRenderAsync` when `firstRender` is true.
- JavaScript calls C# with `[JSInvokable]`: static with `DotNet.invokeMethodAsync`, instance with `DotNetObjectReference`.
- Catch `JSException`. Dispose module and object references when the component is removed.

Next: **Dependency Injection**
