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.
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.
Expose the function by assigning it to a property of window
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 (e.g. your channel), see this answer.
In Greasemonkey/Firemonkey you'll also have to use exportFunction
.