What is the most effective way to send messages from Typescript to C#?

Could someone provide guidance on how to properly send a message from Typescript to C#? I have been attempting to receive the message in C# using WebView_WebMessageReceived with the code snippet below:

private void WebView_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e)
        {
            var json = e.TryGetWebMessageAsString();
        }

In my typescript file, I have tried the following approaches:

window.chrome.webview.postMessage("test");   
window.postMessage("test", '*');
window.postMessage({type: 'hello', payload: {}}, '*');

However, it seems that the message is not getting through to C#. Interestingly, the above code functions as expected in plain HTML but not in TypeScript. Any suggestions or insights would be greatly appreciated.

Answer №1

The description provided seems a bit unclear regarding the title. It appears that there may be an issue with calling the

window.chrome.webview.postMessage
method from a TypeScript file, resulting in an error.

To successfully call the

window.chrome.webview.postMessage
method within a TypeScript file, it is necessary to extend the Window type definition.

In my own project, I addressed this by creating a separate file named global.d.ts and adding the following code:

export {};

declare global {
  interface Window {
    chrome: {
      webview: {
        postMessage: (message: any) => void;
      };
    };
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with data types error in TypeScript while using Next.js?

I am encountering an issue with identifying the data type of the URL that I will be fetching from a REST API. To address this, I have developed a custom hook for usability in my project where I am using Next.js along with TypeScript. Below is the code sni ...

What is the best way to incorporate jQuery for fading in server controls?

When a click event is triggered in the Code Behind, I have two webform panels that are displayed or hidden accordingly. The initial setup looks like this: pnlStepOne.Visible = true; pnlStepTwo.Visible = false; Upon clicking a button (#btnStepOne), the vi ...

Encountering a Typescript error while attempting to extract state from a History object containing an enum property

My enum structure is as follows: enum values { first, second, } Within my component, I handle the history object like this: const { push, location: { state = {} } } = useHistory(); Additionally, in the same component within a useEffect hook, I have ...

Learn how to display or conceal the HTML for 'Share this' buttons on specific routes defined in the index.html file

Currently, I am in the process of updating an existing Angular application. One of the requirements is to hide the "Share this buttons" on specific routes within the application. The "Share" module typically appears on the left side of the browser window a ...

TypeScript does not properly validate the types of defaultProps

When working with TypeScript 3.0, I consulted the documentation at https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html The recommendation is to use static defaultProps: Pick<Props, "name"> as an explicit type annotation ...

What is the reason for VS Code recognizing an import as valid while WebPack does not approve it?

I believe the root of the problem lies in the version of WebPack I am using ("webpack-cli": "3.3.11"). Before embarking on another round of debugging to upgrade WebPack (attempted version 5 but faced issues due to lack of a config file) ...

Guide for adjusting icon dimensions in Material-UI breakpoints

import { Container } from "@mui/material"; import * as React from "react"; import { Home } from "@mui/icons-material"; import PersonIcon from "@mui/icons-material/Person"; import FormatListBulletedIcon from "@mu ...

Lack of Intellisense in Sveltekit for the generated $types module on WebStorm

Is there a setting in WebStorm to enable intellisense for automatically generated ./$types by SvelteKit? I'm writing without any minimal example, just curious. Everything is done according to SvelteKit's documentation. Using satisfies LayoutLoad ...

A specialized type that guarantees a string union includes a particular string literal

I need to define a Mapped type that specifies a field named status which can be either a string or the string value ready: This example works as expected: export type ValidServiceState = HasReady<{ status: "ready" }>; The following should ...

Compiling async code with generators in Typescript proves to be challenging

Scenario As I delve deeper into Typescript, I've come across the advice that blocking calls should not be made within asynchronous code. I have also found generators to be helpful in simplifying directory traversal and preventing stack overflow. ...

What is the process for populating a date picker with dates sourced from a database?

Can you help me with a problem I'm facing? I need to populate a date picker with specific dates that are stored in the database. Is there a method to achieve this, like filling the date picker directly from the database? datePicker.fill(DbContext.Fro ...

Guide to adding information to a table with the help of an "interface" in Angular 6 and utilizing Typescript

Looking for some guidance with Angular as I am just starting out. I am currently trying to send an API request in angular 6 using Typescript. However, I am facing difficulties when it comes to adding data to a table. Check out my code on: Codepen In my p ...

Troubles encountered while attempting to properly mock a module in Jest

I've been experimenting with mocking a module, specifically S3 from aws-sdk. The approach that seemed to work for me was as follows: jest.mock('aws-sdk', () => { return { S3: () => ({ putObject: jest.fn() }) }; }); ...

Is it possible to schedule deployments using Vercel Deploy Hooks in Next.js?

When we schedule a pipeline on git, I want to schedule deploy hooks on vercel as well. Since the app is sending getStaticProps and every HTTP request will be run on every build, I have to rebuild the site to get new results from the server. For instance, ...

What is the best way to change an existing boolean value in Prisma using MongoDB?

Exploring prisma with mongoDb for the first time and faced a challenge. I need to update a boolean value in a collection but struggling to find the right query to switch it between true and false... :( const updateUser = await prisma.user.update({ where: ...

"Error: The update depth has exceeded the limit while trying to use the

I've been working on implementing localStorage in NextJs using TypeScript by following this guide at , but I am encountering an error. https://i.sstatic.net/NX78a.png Specifically, the error occurs on the context provider repeatedly. Below is the c ...

Guide on how to address the problem of the @tawk.to/tawk-messenger-react module's absence of TypeScript definitions

Is there a way to fix the issue of missing TypeScript definitions for the @tawk.to/tawk-messenger-react module? The module '@tawk.to/tawk-messenger-react' does not have a declaration file. 'c:/develop/eachblock/aquatrack/management-tool-app ...

Invoke the controller using the Url.Action method

In my current setup, I am utilizing Url.Action to create the following HTML link: <a href='@Url.Action("AddToCart", "Shop ", new {<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="770716050304281e134a373a1813121b592716050 ...

Generate user-customized UI components from uploaded templates in real-time

Summary: Seeking a solution to dynamically generate UI pages using user-provided templates that can be utilized for both front-end and back-end development across various use cases. Ensuring the summary is at the top, I am uncertain if this question has b ...

Can child components forward specific events to their parent component?

I created a basic component that triggers events whenever a button is clicked. InnerComponent.vue <template> <v-btn @click="emit('something-happened')">Click me</v-btn> </template> <script setup lang=" ...