简体   繁体   中英

How do I make a JavaScript script run every time a specific page loads. Browser: Edge (I'm using tampermonkey)

Ok, the title may be a little confusing, but my goal is to use tampermonkey, to make a userscript that declares a function that I can use in the console every time a page (discord) loads. This is what my userscript looks like:

// ==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();
  }
  
})();

To clarify again, I want to put the code above into a userscript. And I want to be able to call the alert1(); from the console.

  1. Replace channels/@me with * in @match so it becomes https://discord.com/*

    It's necessary because discord is a modern SPA (Single-Page Application) which imitates navigation using history.pushState API so if you open the main page first and then navigate to your channel, there will be no page load event meaning that userscript won't run on such change of the URL.

    So, previously, your userscript didn't run on the initial page and it never ran afterwards.

    Now it runs exactly once on the initial page whether it's your channel or not.

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

  3. Remove the outer function wrapper, more info .

Here's the entire code after // ==/UserScript==

'use strict';

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

If you want to expose multiple functions, use a shorthand declaration to avoid duplication of code:

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

If you want to use @grant like GM_setValue , replace window with unsafeWindow in the above code.

If you want to run code when the URL matches something (eg your channel), see this answer .

In Greasemonkey/Firemonkey you'll also have to use exportFunction .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM