A. *_*ner 6 javascript json greasemonkey userscripts tampermonkey
我有一个index.html调用外部 URL的页面。这个外部 URL 是一个 JSON 端点。换句话说,当我打开开发工具(使用F12)时,我看到两个资源:index.html和myJSONEndpoint。
我希望每次加载时都能获取该 JSONindex.html并对其进行处理。
Greasemonkey 或 Tampermonkey 能做到这一点吗?
页面示例:
<!doctype html>
<html>
<head>
<title>Weather</title>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
}
};
xmlhttp.open("GET", "https://api.weather.gov/points/39.7456,-97.0892", true);
xmlhttp.send();
</script>
</head>
<body>
<p>Page Loaded...</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
当我加载该页面时,开发工具中会出现两个请求。基本索引页面和 JSON 请求。
我想获取 JSON 内容并将其推送到 DOM 上。然后用户可以从那里复制/粘贴。
创建一个新的<div>然后将内容粘贴在那里?
关于:
好的,那么也许只是获取 JSON 内容并推送到 DOM 更容易?然后用户可以从那里复制/粘贴。
好的,下面的代码显示了如何做到这一点。
请注意,您指定的 JSON URL 本身不提供天气数据。 它指向正确的位置以获取指定坐标的数据。
下面是一个完整的工作 Tampermonkey 脚本。它将第一次JSON 调用中的信息添加到 Stack Overflow 问题的左列,例如(单击图像查看大图):
// ==UserScript==
// @name _Fetch and use JSON
// @match /sf/*
// @require https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @connect api.weather.gov
// ==/UserScript==
/* global $ */
/* eslint-disable no-multi-spaces, curly */
var apiURL = "https://api.weather.gov/points/39.7456,-97.0892";
GM_xmlhttpRequest ( {
method: "GET",
url: apiURL,
responseType: "json",
onload: processJSON_Response,
onabort: reportAJAX_Error,
onerror: reportAJAX_Error,
ontimeout: reportAJAX_Error
} );
function processJSON_Response (rspObj) {
if (rspObj.status != 200 && rspObj.status != 304) {
reportAJAX_Error (rspObj);
return;
}
//-- The payload from the API will be in rspObj.response.
var pyLd = rspObj.response;
/*-- The rest is defined by the structure specified/returned by the API.
See its docs for more.
*/
var nearbyCity = pyLd.properties.relativeLocation.properties.city;
var usaState = pyLd.properties.relativeLocation.properties.state;
var forecastURL = pyLd.properties.forecast;
//-- Add the info to a div and insert that div somewhere...
var resultsDiv = $( `
<div id="tmJsonMashupResults">
For ${nearbyCity}, ${usaState}; you can see the forecast (JSON) at
<a href="${forecastURL}">this link</a>.
</div>
` );
var targetNd = $("#left-sidebar > div > nav[role='navigation']");
if (targetNd.length)
targetNd.append (resultsDiv);
else
console.error ("TM scrpt => Target node not found.");
}
function reportAJAX_Error (rspObj) {
console.error (`TM scrpt => Error ${rspObj.status}! ${rspObj.statusText}`);
}
//-- Style the results:
GM_addStyle ( `
#tmJsonMashupResults {
color: black;
background: #f9fff9;
padding: 0.75ex 1.3ex;
border: 1px double gray;
border-radius: 1ex;
}
` );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9911 次 |
| 最近记录: |