javascript - tampermonkey 脚本跨多个页面运行
问题描述
这是我想做的一个例子。每当我们在目标 url 上时,即 stackoverflow 会在底部出现一个带有按钮的粘性页脚。在搜索中键入内容的按钮之一,提交表单。在此之后它等待页面加载并执行刚刚加载的页面,即点击第一个链接。
我发现这不可能通过在提交后运行单击来实现,因为页面的框架发生了变化或类似的事情,怎么可能用 Tampermonkey 做到这一点。
// ==UserScript==
// @name New Userscript
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match https://stackoverflow.com/
// @grant none
// ==/UserScript==
(function() {
'use strict';
$('body').append('<div id="test"><p><button onclick="myFunction()">Click me</button></p></div>');
$('body').append(
`<script type="text/javascript">
function myFunction() {
// page 1
document.querySelector('#search > div > input').value="tampermonkey";
document.forms[0].submit();
// page 2 (DOEST WORK)
document.querySelector('#question-summary-29592068 > div.summary > div.result-link > h3 > a');
}
</script>`
);
$('#test').css({'position': 'fixed',
'left': '0',
'bottom': '0',
'width': '100%',
'background-color': 'red',
'color': 'white',
'text-align': 'center',
'z-index':'1'
});
})();
解决方案
您的脚本可能无法正常工作的一个原因是因为在脚本顶部它说
// ==UserScript==
// @name New Userscript
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match https://stackoverflow.com/
// @grant none
// ==/UserScript==
stackoverflow.com 主页上// @match
唯一不包含搜索页面的// @match https://stackoverflow.com/*
匹配项,因此 @match 应该与主页和搜索页面匹配。你也应该让它成为“点击我!” 按钮仅通过使用if
语句显示在主页上。如果您愿意,我也完全解决了您的问题。
// ==UserScript==
// @name New Userscript
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match https://stackoverflow.com/*
// @grant none
// ==/UserScript==
window.onload = function() {
'use strict';
if (location.href == "https://stackoverflow.com/search?q=tampermonkey") {
alert(document.querySelector('#question-summary-29592068 > div.summary > div.result-link > h3 > a'));
}else {
$('body').append('<div id="test"><p><button onclick="myFunction()">Click me</button></p></div>');
$('body').append(
`<script type="text/javascript">
function myFunction() {
// page 1
document.querySelector('#search > div > input').value="tampermonkey";
document.forms[0].submit();
}
</script>`
);
$('#test').css({
'position': 'fixed',
'left': '0',
'bottom': '0',
'width': '100%',
'background-color': 'red',
'color': 'white',
'text-align': 'center',
'z-index':'1'
});
}
};
推荐阅读
- iis - 未针对 IIS 网站绑定 Google Cloud 列出外部 IP 地址
- azure - 如何从 Azure 上运行的 Web 应用连接到远程 API
- tomcat - 如何在 Tomcat 控制台日志中记录 sessionId?
- android - 从带有附加功能的命令行终端启动快捷方式?
- html - 将基本身份验证与 Web 应用程序和 CDN 结合使用的最简化方式
- javascript - 如何将焦点设置在 onRowClicked 行中的第一个可编辑单元格上?
- java - 使用 Java 中的构造函数初始化二维数组
- mysql - 迭代列以显示时间之间的计数
- sql - 需要帮助定位 SQL 列中的特定字符
- excel - 创建 Excel 公式以从另一行返回特定的非空白映射值