要在油猴脚本(Tampermonkey 或 Greasemonkey)中调用题库API,可以按照以下步骤操作:
-
创建一个新的油猴脚本:
- 打开 Tampermonkey/Greasemonkey 控制面板。
- 点击“新建脚本”按钮。
-
设置元数据块:
- 在脚本的元数据块中,定义脚本的基本信息,并添加跨域请求所需的权限。
-
编写脚本:
- 使用
GM_xmlhttpRequest
方法来发送 HTTP 请求,这是油猴脚本提供的一个特殊方法,允许你发送跨域请求。
- 使用
详细步骤说明:
-
设置元数据块:
@grant GM_xmlhttpRequest
:这是必要的权限,允许脚本使用GM_xmlhttpRequest
进行跨域请求。
-
编写 API 调用逻辑:
GM_xmlhttpRequest
:这个方法用来发送 HTTP 请求。我们在示例中使用 GET 方法,你也可以根据需要使用 POST、PUT 等方法。headers
:根据 API 要求设置请求头。如果 API 需要认证,添加相应的认证信息。onload
:这是请求成功时的回调函数。在这里处理 API 返回的数据。onerror
:这是请求失败时的回调函数。在这里处理错误情况。
需要注意的事项:
- 确保 API 允许跨域请求(CORS)。如果 API 端没有正确配置 CORS,可能会导致请求失败。
- 根据 API 文档,正确设置请求方法和请求头。
- 替换示例中的
apiUrl
和Authorization
信息为你的实际 API 端点和认证信息。
示例
以下是一个基本的油猴脚本示例,展示了如何调用一个题库API并在控制台中输出结果:
// ==UserScript==
// @name Tiku API Caller
// @namespace http://tampermonkey.net/
// @version 0.1
// @description Call Tiku API from Tampermonkey script
// @author You
// @match *://*/*
// @grant GM_xmlhttpRequest
// ==/UserScript==
(function() {
'use strict';
// Replace with your Tiku API endpoint
const apiUrl = 'https://api.example.com/tiku';
// Function to call the Tiku API
function callTikuApi() {
GM_xmlhttpRequest({
method: 'GET',
url: apiUrl,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_ACCESS_TOKEN' // Replace with your actual token if required
},
onload: function(response) {
if (response.status === 200) {
const data = JSON.parse(response.responseText);
console.log('Tiku API Response:', data);
} else {
console.error('Error calling Tiku API:', response.statusText);
}
},
onerror: function(error) {
console.error('Request Failed:', error);
}
});
}
// Call the Tiku API when the script is loaded
callTikuApi();
})();
免费接口:
//接口
//https://zr.026wk.xyz/api/freeapi.php
//data{
//question=question
//}
//返回answer=answer
//接口可对接一切程序,公众号小程序/html/php/等等