javascript - 使用 // @grant GM_xmlhttpRequest 将此代码转换为 Tampermonkey
问题描述
这是代码:我想尝试获取数据,但一切都在这里,请翻译成 Tampermonkey 语言
var xhr = new XMLHttpRequest();
// getting datas
xhr.open("GET", "https://brainly.in/api/28/api_users/me", true);
xhr.onload = function () {
if (this.status === 200){
var data = JSON.parse(xhr.responseText);
var nick = data.data.user.nick;
var privlage = data.data.user.privileges;
alert(`The nick is ${nick} and privileges are ${privlage.join(',')}`
}else{
alert("Failed to load API")
}
};
xhr.send(data);
解决方案
文档为GM_xmlhttpRequest
移植您的本机提供了足够的信息XMLHttpRequest
。
我提供了帮助函数来提供自记录代码。
另请参阅:Tampermonkey:文档:GM_xmlhttpRequest
// ==UserScript==
// @name Brainly User Info
// @namespace in.brainly.api
// @version 1.0.0
// @description Retrieves information about a user uising the API.
// @author MrPolywhirl
// @match https://stackoverflow.com/questions/*
// @grant GM_xmlhttpRequest
// ==/UserScript==
(function() {
'use strict';
const API_USER_GET = (id) => `https://brainly.in/api/${id}/api_users/me`;
const main = () => {
fetchUserInfo({
id: 28,
callback: (response) => {
const user = response.data.user;
const nick = user.nick;
const privileges = user.privileges.join(',');
alert(`The nick is ${nick} and privileges are ${privileges}`;
}
});
};
const fetchUserInfo = (config) => {
config = config || {};
if (config.id == null) {
throw new Error('Did not supply a user id!');
}
if (config.callback == null) {
throw new Error('Did not supply a callback function!');
}
GM_xmlhttpRequest({
method: 'GET',
url: API_QUESTIONS_GET(config.id),
headers: {
'Content-Type': 'application/json'
},
onload: (response) => {
config.callback(JSON.parse(response.responseText));
},
onerror: () => {
console.error('Failed to load API');
}
});
};
main();
})();
这是一个更通用的用户脚本,适用于 Stack Overflow:
// ==UserScript==
// @name Stack Overflow Question Info
// @namespace com.stackoverflow.userscripts
// @version 1.0.0
// @description Present information about a question.
// @author MrPolywhirl
// @require https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js
// @match https://stackoverflow.com/questions/*
// @grant GM_xmlhttpRequest
// ==/UserScript==
/* global moment */
(function() {
'use strict';
const API_QUESTIONS_GET = (id) => `https://api.stackexchange.com/2.2/questions/${id}?site=stackoverflow`;
const main = () => {
fetchQuestionInfo({
callback: (response) => {
const question = response.items[0];
const creationDate = new Date(question.creation_date * 1000);
console.log(`Date: ${moment(creationDate).format('YYYY-MM-DD')} | Title: "${question.title}"`);
}
})
};
const fetchQuestionInfo = (config) => {
config = config || {};
if (config.callback == null) {
throw new Error('Did not supply a callback function!');
}
GM_xmlhttpRequest({
method: 'GET',
url: API_QUESTIONS_GET(retrieveQuestionId()),
headers: {
'Content-Type': 'application/json'
},
onload: (response) => {
config.callback(JSON.parse(response.responseText));
}
});
};
const retrieveQuestionId = () => {
const pathArray = window.location.pathname.split('/'),
foundIndex = pathArray.indexOf('questions');
return foundIndex > -1 ? parseInt(pathArray[foundIndex + 1], 10) : -1;
};
main();
})();
推荐阅读
- xml - 找不到元素“汽车”的声明
- amazon-web-services - 如何在 AWS LightSail Linux 实例上打开端口 25
- android - 从 Android 中的 Firebase 实时数据库中检索数据 - recyclerview
- list - 如何应用断言条件来更改列表?
- python - 如何从字符串而不是文档字符串运行 doctest 示例?为什么需要缩进?
- html - 为什么 iframe 不继承父级的样式?
- javascript - 如何在 socket.io 上获取 https
- azure - 如何在 Azure 数据工厂中获取管道文件夹路径?
- go - 在golang中获取数组的长度并将其存储在const中
- c# - 相机中的 UnassignedReferenceException