首页 > 解决方案 > 使用 // @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);

标签: javascripttampermonkey

解决方案


文档为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();
})();


推荐阅读