[英]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.好的,标题可能有点令人困惑,但我的目标是使用 tampermonkey,制作一个声明 function 的用户脚本,我可以在每次加载页面(不和谐)时在控制台中使用它。 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();
我希望能够调用
alert1();
from the console.从控制台。
Replace channels/@me
with *
in @match
so it becomes https://discord.com/*
将
channels/@me
替换为@match
中的*
,使其变为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.这是必要的,因为 discord 是现代 SPA(单页应用程序),它使用
history.pushState
API 模拟导航,因此如果您先打开主页然后导航到您的频道,则不会出现页面加载事件,这意味着用户脚本不会在 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
通过将 function 分配给
window
的属性来公开它
Remove the outer function wrapper, more info .移除外部 function 包装, 更多信息。
Here's the entire code after // ==/UserScript==
这是
// ==/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.如果您想像
@grant
一样使用GM_setValue
,请将上述代码中的window
替换为unsafeWindow
。
If you want to run code when the URL matches something (eg your channel), see this answer .如果您想在 URL 匹配某些内容(例如您的频道)时运行代码,请参阅此答案。
In Greasemonkey/Firemonkey you'll also have to use exportFunction
.在 Greasemonkey/Firemonkey 中,您还必须使用
exportFunction
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.