What is the best way to execute a JavaScript script each time a particular webpage is loaded? My browser is Edge and I am utilizing Tampermonkey for this task

Hey there, I know the title might seem confusing but my aim is to utilize tampermonkey to create a userscript that defines a function which I can execute in the console whenever a page (like Discord) loads. The userscript code appears like this:

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://discord.com/channels/@me
// @grant        none
// ==/UserScript==

(function() {
  'use strict';
  
  function alert1() {
    alert();
  }
  
})();

Just to reiterate, I wish to embed the above code into a userscript. And then I would like to be able to invoke the alert1(); from the console.

Answer №1

  1. Modify channels/@me to * in @match so it changes to https://discord.com/*

    This adjustment is important as Discord operates as a modern SPA (Single-Page Application) that simulates navigation through the use of the history.pushState API. Without this modification, when you initially open the main page and then navigate to your channel, there won't be a page load event triggering the userscript to run on URL changes.

    Prior to this change, the userscript wouldn't execute on the main page or any subsequent pages.

    Now, it will run once on the initial page regardless of whether it's your channel or not.

  2. Make the function accessible by assigning it to a property of window

  3. Eliminate the outer function wrapper for more streamlined functionality, refer to more information.

Below is the complete code after // ==/UserScript==

'use strict';

window.alert1 = function alert1() {
  alert('foo');
}

If you wish to expose multiple functions, utilize shorthand declaration to prevent redundant code:

Object.assign(window, {
  foo() {
    alert('foo');
  },
  bar() {
    alert('bar');
  },
});

In case you need to use @grant such as GM_setValue, replace window with unsafeWindow in the provided code snippet.

To implement actions based on specific URL matches (e.g., your channel), refer to this response.

If operating with Greasemonkey/Firemonkey, remember to include exportFunction for functionality.

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

Fetching a URL from within a PHP file using AJAX

I am fairly new to creating web applications, so please bear with me if I am not using the correct technical terms. I came across this code for using a web proxy, but it doesn't seem to be working. I suspect that the issue lies in it not retrieving th ...

What are the best practices for effectively managing jQuery UI sliders?

I am currently developing a web application that involves updating jQuery UI sliders using JavaScript. While I have managed to resolve most of the issues related to updating the slider after initialization, there is one particular issue that remains unreso ...

Showcasing two sets of data from an array using chart.js within a node.js environment

I am currently working on a project where I need to display two elements from an array - one as the label (e.g. "name of certain type of crop") and the other as the data itself (e.g. "quantity of the crop"). However, I am facing an issue where if the same ...

The requested style from ' was denied due to its MIME type ('text/html') not being compatible with supported stylesheet MIME types, and strict MIME checking is enforced

It's strange because my style.css file in the public folder works on one page but gives me an error on another. I'm not sure why it would work on one page and not on the other. The CSS is imported in index.html so it should work on all pages of t ...

Issue with loading HTML file correctly in Django

I have been attempting to integrate my Django app with an admin dashboard from a repository on GitHub. After successfully logging in, the app redirects to the dashboard, but only the HTML part loads and none of the fancy features are visible on the dashboa ...

Refreshing the DOM following an API call using VueJS

Struggling with updating the DOM after fetching data from an API. Although my object is successfully fetching the data, the DOM renders before receiving the API Data and fails to update afterward. I'm puzzled as to why it's not refreshing itself ...

Managing background tasks with Node.js in real-time

I am currently faced with the challenge of managing background events. When a user is temporarily banned, we save the ban expiration in our database to ensure they are unbanned at the right time. However, my current code checks every ban every 10 seconds ...

Adjusting Javascript code to launch a URL in a new window or new tab depending on the user's selection

I seem to be encountering a puzzling issue with a link on my website. When clicked normally, the link opens in a new window. However, if I right-click and select "open in new window" or "open in new tab," it just reloads the same page where the link was cl ...

The peculiar behavior of Google Maps markers refreshing inconsistently upon bounds adjustment

I recently completed a project involving a restaurant app using Vue and Google Maps. While everything is functional, I have encountered a persistent bug with the markers. When navigating on the map and the bounds change, some markers seem to disappear. Ev ...

Filtering out specific properties from an element within a JavaScript forEach loop

const findBloodType = bloodCodeArray.find(bloodCode => bloodCode.code.toUpperCase() === bloodType.toUpperCase()).code; In my Angular code, I am trying to retrieve just the 'code' property of the 'bloodCode' element using a callback ...

Having difficulty assigning properties in react-redux

I'm experiencing an issue with my code that involves using both React and Redux. The problem lies in the fact that this.props.comments is coming up as undefined. Can anyone identify what may be amiss? reducer.js: import {Map,List} from 'immutab ...

Transferring information between components within AngularJS

export class AppComponent { title = 'shopping-cart'; ngOnInit() { } images = [ { title: 'At the beach', url: 'https://images.unsplash.com/photo-1507525428034-b723cf961d3e?ixlib=rb-4.0.3&ixid=MnwxMjA ...

Dynamic loading of tinymce in progress

When tinymce is loaded in the head and before dom, everything works fine. However, if I attempt to load the JavaScript with ajax using jquery.getScript(), it doesn't work. I initialize tinymce when the user clicks the content area, so the dom must be ...

Unable to transfer array elements to a function within PhantomJS

I am facing a challenge in extracting the source code from multiple webpages simultaneously. The links are stored in an array from a source text file. While I am able to successfully loop through the array and display the links, I encounter an issue when p ...

How to locate the duplicate elements within an array using JavaScript

There are two different sets of numbers Numbers1=[ 0, 1, 2, 0, 2 ]; Numbers2=[ 0, 0, 1, 2, 2 ]; The goal is to determine the index of each element in Numbers2 from Numbers1 and create a new array like [0,3,1,2,4]; If you would like to see the code I wr ...

What is the best way to extract elements from an array object and store them in a separate array using JavaScript

Is there a way to extract specific values from an array object and store them in individual variables as arrays? // Given array const dummy = [ { id: 1, name: 'John', }, { id: 2, name: 'Jane', }, { id: 3, ...

Unpredictable jQuery Ajax setTimeout

I have a script that retrieves data from ajax.php and displays it in a div. The intention is for the information to be shown for a period of 3 seconds before hiding the #ajax-content and displaying #welcome-content. Most of the time it works as intended, ...

Learn how to manipulate Lit-Element TypeScript property decorators by extracting values from index.html custom elements

I've been having some trouble trying to override a predefined property in lit-element. Using Typescript, I set the value of the property using a decorator in the custom element, but when I attempt to override it by setting a different attribute in the ...

Guiding Through Bootstrap 5.2 Tabs Using External Buttons

I am currently in the process of designing a form that will be spread out across 4 tabs. Rather than having the tabs at the top for easy navigation, I want to include a set of PREVIOUS/NEXT buttons within each tab. HTML: <div class="setupForm" ...

Unlock the navigation tab content and smoothly glide through it in Bootstrap 4

Hey there, I have managed to create two functions that work as intended. While I have some understanding of programming, I lack a background in JavaScript or jQuery. The first function opens a specific tab in the navigation: <script> function homeTa ...