需求:
在不修改代码的情况下修改程序执行的功能,我们也称为hook技术。我想加一个获取输入框数值到达18位自动发送http请求到后端检索数据库。难点是CORS安全问题和iframe嵌套问题,这里是使用油猴脚本自带的发送功能规避cors问题。
解决办法:
油猴脚本注入js
具体步骤:
0.创建示例文本框
创建一个文件
3.html
<iframe name="tabContent_A0000001A02000791921D994FECB3C85E05310380C5D0AEA" src="2.html" style="width: 400px; height: 200px;"></iframe>
2.html
<!DOCTYPE html>
<html>
<head>
<title>MyIframe</title>
<style>
body {
font-family: Arial, sans-serif;
}
input[type="text"] {
padding: 10px;
font-size: 16px;
}
</style>
</head>
<body>
<input type="text" id="dksbdForm_skfnsrsbh" placeholder="请输入文本">
<script>
const myInput = document.getElementById('dksbdForm_skfnsrsbh');
myInput.addEventListener('input', function(event) {
console.log('输入框值改变了');
console.log('当前值:', this.value);
});
</script>
</body>
</html>
1.在浏览器安装油猴插件
2.导入脚本配置
// ==UserScript==
// @name 输入框监测示例
// @namespace http://60.164.245.85:8888/
// @version 1.0
// @description 获取并打印输入框的值
// @match http://60.164.245.85:8888/*
// @grant GM.xmlHttpRequest
// ==/UserScript==
(function() {
'use strict';
// 获取 iframe 的引用
const iframeElement = document.querySelector('iframe[name="tabContent_A0000001A02000791921D994FECB3C85E05310380C5D0AEA"]');
// 确保 iframe 以及 iframe 的 contentWindow 和 contentDocument 加载完成
iframeElement.onload = function() {
const iframeDocument = iframeElement.contentDocument;
const inputElement = iframeDocument.getElementById('dksbdForm_skfnsrsbh');
// 在父页面中监听 iframe 内的输入框事件
inputElement.addEventListener('input', function(event) {
// console.log('输入框值改变了');
// console.log('当前值:', this.value);
// 获取输入框的值
var inputValue = inputElement.value;
// 移除输入值中的非数字字符
var numbers = inputValue.replace(/\D/g, "");
// 检查是否输入了18位数字
if (numbers.length === 18) {
// 打印输入框的值
let postData = 'data=' + encodeURIComponent(numbers);
console.log("输入框的值为:" + numbers);
// 发送请求到后台
// 发送POST请求
GM.xmlHttpRequest({
method: 'POST',
url: 'http://127.0.0.1:8080/api/data',
data: postData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
onload: function(response) {
// 请求成功后的处理逻辑
console.log('提交成功');
alert(response.responseText);
},
onerror: function(response) {
// 请求失败后的处理逻辑
console.log('提交失败');
console.log(response.responseText);
}
});
}
});
};
})();
3.编写后台示例
这是编写一个springboot的demo
package com.ruoyi.system.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ApiController {
@PostMapping("/data")
public String receiveData(@RequestBody String data) {
// 处理油猴脚本发送的数据
System.out.println("Received data from Greasemonkey script: " + data);
// 可以在这里编写逻辑来处理接收到的数据,如保存到数据库,发送通知等
return "恭喜你查询成功,你的输入值是:"+data+",该人有不良记录";
}
}
3.访问3.html,在输入框中输入数字触发http请求查看弹窗