At simple BlazorBrowserExtension i’m trying to call a c# method marked with the [JSInvokable] from BackgroundWorker.js extension file.
According to documentation the project structure:
FilesChooser.cs
public class FilesChooser
{
public FilesChooser(string? name)
{
Name = name ?? "No Name";
}
public string? Name { get; set; }
[JSInvokable]
public string GetHelloMessage() => $"Hello, {Name}!";
}
JsInteropClasses3.cs
public class JsInteropClasses3
{
private readonly IJSRuntime js;
public JsInteropClasses3(IJSRuntime js)
{
this.js = js;
}
public async ValueTask<string> CallHelloHelperGetHelloMessage(string? name)
{
using var objRef = DotNetObjectReference.Create(new FilesChooser(name));
return await js.InvokeAsync<string>("GetHelloMessage", objRef);
}
}
And it works well on Index.razor
@code {
private string? name;
private string? result;
private JsInteropClasses3? jsInteropClasses;
protected override void OnInitialized()
{
jsInteropClasses = new JsInteropClasses3(JS);
}
private async Task TriggerDotNetInstanceMethod()
{
if (jsInteropClasses is not null)
{
result = await jsInteropClasses.CallHelloHelperGetHelloMessage(name);
}
}
}
But when i’m calling it from BackgroundWorker.js nothing hapends (obviously falling with exseptions):
import * as _ from "/content/Blazor.BrowserExtension/lib/browser-polyfill.min.js";
browser.runtime.onInstalled.addListener(() => {
const indexPageUrl = browser.runtime.getURL("index.html");
browser.tabs.create({
url: indexPageUrl
});
});
browser.runtime.onMessage.addListener(function (request, sender, sendResponse) {
// Callback for that request
let rez = '';
browser.invokeMethodsAsync = async (element) => {
rez = await element.dotNetHelper.invokeMethodAsync('GetHelloMessage');
sendResponse({ message: "Background has received that message ????" + rez});
}
return true; // Add return true to fix the error.
});
What can be done in this situation?