Utilize a JavaScript <script> tag on a single razor page

Is it possible to use a specific .js file just inside a particular razor page when using blazor and .Net 5?

Just to provide some context, I created a simple script named MyJavaScript.js:

function myfunction()
  {
    alert("Hello");
  }

I then added this script to _host.cshtml:

<script src="/MyJavaScript.js"></script>

Currently, whenever I navigate to any razor page in my web app (e.g., localhost:1212, localhost:1212/counter), the .js file is loaded on the first visit and accessible across all razor pages. However, I am interested in restricting the usage of this .js file to just one specific razor page (mypage.razor). Is there a way to achieve this?

In simpler terms, I want only localhost:1212/mypage to display the alert and have access to myfunction, rather than making it available across all razor pages. Where should I place the MyJavaScript.js file to accomplish this?

Update 1: It seems that placing the <script></script> tag inside a component is not supported.

https://i.sstatic.net/lcfAj.jpg

Answer №1

Based on your screenshot, it seems like you're close to the solution - all you need to do is import the JavaScript module using IJSRuntime and then call the function as usual with IJSObjectReference. Just ensure that your JavaScript file function includes the export keyword.

The code snippet provided above gives a clear example for .NET 5:

// wwwroot/scripts.js
export function showPrompt(message) {
  return prompt(message, 'Type anything here');
}
@page "/call-js-example-6"
@implements IAsyncDisposable
@inject IJSRuntime JS

<h1>Call JS Example 6</h1>

<p>
    <button @onclick="TriggerPrompt">Invoke browser window prompt</button>
</p>

<p>
    @result
</p>

@code {
    private IJSObjectReference module;
    private string result;

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

    private async Task TriggerPrompt()
    {
        result = await Prompt("Enter some text");
    }

    public async ValueTask<string> Prompt(string message)
    {
        return await module.InvokeAsync<string>("showPrompt", message);
    }

    async ValueTask IAsyncDisposable.DisposeAsync()
    {
        if (module is not null)
        {
            await module.DisposeAsync();
        }
    }
}

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

Why aren't my Post Variables being passed through my jQuery Ajax Request?

My goal is to utilize a full calendar ajax call to add events to the database. After testing the PDO query separately and confirming its functionality, I have identified an issue with the ajax post. The code snippet below showcases the ajax call in defaul ...

When it comes to TypeScript, one can always rely on either event.target or event

I'm a beginner with TypeScript and currently in the process of refactoring an arrow function within React.js. Here is the current implementation: handleChange = (event): void => { const target = event.target || event.srcElement; this.s ...

alerts and malfunctions encountered while using Karma and Chrome

I am currently delving into AngularJS using the book 'AngularJS Up and Running' by O'Reilly. I've reached the chapter on unit testing with Karma & Jasmine, but I'm encountering difficulties in getting it to work. UPDATE: After cha ...

Incorporating an external JavaScript file into an AngularJS project

index.html: <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> <script src="./assets/namesController.js"></script> <body ng-app="myApp"> < ...

What is the process for attaching an on-click event listener by utilizing an argument that is passed to a function in JavaScript?

These are the functions I have created: function type(message) { document.getElementById("body").innerHTML="<div id=\"textbox\" class=\"textbox\"></div><div id=\"oc\&q ...

Running a loop to animate in a callback function

Inside the function updateMapColor, the colors of a world map change based on the input year. I have tried to animate the color change over multiple years by calling updateMapColor, but it is not working. Do I need to incorporate setInterval? If so, could ...

Ways to verify HTML code consistency for mobile phone web applications on various devices

I am in the process of developing a mobile-friendly HTML/JavaScript web page that needs to be functional on older mobile devices as well. This webpage will consist of select lists, buttons, links, and basic JavaScript for some variables. Is it feasible ...

What is the best way to manage data in a single-page application and retrieve it after the page has been refreshed?

Lately, I’ve encountered an issue with data storage in a single-page application. I’m seeking some guidance on how to effectively store data and retain it after refreshing the page within a Single Page Application. As an example, let's say I hav ...

Angular allows you to set specific conditions for when a failed HTTP request should be retried, and you can also specify the number of attempts that should be

Within my angular application, I have a post request that needs to be retried based on the error message, but with a limit on the number of attempts. Initially, I attempted the following approach: public post(url, data) { this._http.post(url, data).pi ...

Use JSON to initiate opening a new tab in JavaScript code

Javascript Code: <script type="text/javascript"> function SaveCustomerInformation() { var data = { SpecialStatusId: AnaOzelDurumId.GetValue(), ContactPersonId: AnaİlgiliPersonelId.GetValue(), }; ...

Capturing and Receiving Voice Audio in DiscordJSv14

Currently, I am developing a Discord bot in JS using DiscordJSv14 and I want the bot to extract audio from a voice chat and forward it to another bot, functioning like a spy or eavesdropper bot. Although I have successfully connected the bot to the voice ...

What could be the reason for XMLHttpRequest to freeze with no error until it reaches the default browser timeout limit

As a front end developer, I have some gaps in my understanding of how networks operate. When a Javascript XMLHttpRequest times out, the ontimeout handler gets triggered. In case the XMLHttpRequest.timeout property is not set (which is supported in modern b ...

Guide on utilizing direction.set within threejs for Vector3 types

In the code below, I have defined a plane, wall, and a character. Now, I am trying to set the direction using vector3(). However, I seem to be encountering an issue. Whenever I press the left or right arrow key on the keyboard, I keep receiving the follow ...

There seems to be an issue with the calculation in my React app as it only displays the correct result after the second symbol

I've been developing a react app that features a button labeled "Add" for users to input data to calculate volume. Each line includes two input fields for the thickness and surface area values. I've noticed an issue where, if a user inputs the th ...

Discover the powerful combination of Sweet Alert 2 JS library and seamless Interop in Blazor Server

I am working on a Blazor server app and I want to incorporate SweetAlert2 methods using JavaScript interop instead of the NuGet SweetAlert package. Below is the code snippet: App.razor <body> <Routes @rendermode=RenderMode.InteractiveServer /> ...

Listening to multiple events in AngularJS using `$scope.$on`

I am faced with a situation where I need to respond to two different events being transmitted via $scope.$emit and take action only when both have occurred. For example, if the events are triggered in the following sequence: $scope.$emit('first&apos ...

Executing an action using onclick in JavaScript within a Ruby on Rails environment

I am looking to execute a specific action in the controllers/static_pages_controller.rb file: def fileopen my_file = File.new("public/CHNAME1.txt","w") my_file.write "\tfasf" my_file.close end (I have tested this functi ...

Sequelize: When attempting to use .get({plain: true})) method, an error is returned indicating that .get is

I'm facing a strange issue as I am able to retrieve only the values of an instance in other parts of my code without any problems. Can you spot what might be wrong with my current code? app.get('/profile', checkAuth, function(req, res) { ...

What is the process for turning off a TypeScript rule for a single line of code?

Dealing with Summernote as a jQuery plugin has been a bit of a struggle for me. I'm trying to modify the object without needing type definitions, but TypeScript keeps throwing errors my way. Even after attempting to delete certain keys, I still get th ...

Keep the active button state when it is clicked in React JS within a functional component

When I click on a button, I want to remain in the section while also having the button stay in the background with a color that indicates my selection. This could be for breakfast, lunch, dinner, or any other section. const Categories = ({ categories, fi ...