Search⌘ K
AI Features

Adding a JavaScript Function and Using the Geolocation API

Explore how to integrate JavaScript with Blazor WebAssembly by adding a custom JavaScript function that uses the Geolocation API. Learn how to retrieve the user's latitude and longitude, invoke JS functions from C#, and handle permission requests within the app.

Adding a JavaScript function

We now need to add a class to contain our current latitude and longitude. We will do this by following these steps:

  1. Right-click the wwwroot folder and select the “Add, New Folder” option from the menu.
  2. Name the new folder scripts.
  3. Right-click the scripts folder and select the “Add, New Item” option from the menu.
  4. Enter “javascript” in the Search box.
  5. Select “JavaScript File.”
  6. Name the file bweInterop.js.
  7. Click the “Add” button.

    Tip: In this course, we will be using the bweInterop namespace for our JavaScript code to both structure our code and minimize the risk of naming conflicts.

  8. Enter the following JavaScript:
JavaScript (JSX)
var bweInterop = {};
bweInterop.getPosition = async function () {
function getPositionAsync() {
return new Promise((success, error) => {
navigator.geolocation.
getCurrentPosition(success, error);
});
}
if (navigator.geolocation) {
var position = await getPositionAsync();
var coords = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
};
return coords;
} else {
throw Error("Geolocation is not supported by this browser.");
};
}

The preceding JavaScript code ...