我正在使用Chrome扩展程序获取在线JSON,其中包含有关视频游戏中地图旋转的数据。地图每4小时轮换一次,因此当地图发生变化时,主机端的JSON也会更新。
事情是,(让我们说地图/ JSON在下午3点更新)当我在下午3点之后点击我的扩展按钮时,扩展加载了前一轮的JSON,而不是新的JSON。我希望每次用户点击按钮扩展时,扩展程序都会更新JSON和DOM。这是我的代码:
的manifest.json
{
"manifest_version": 2,
"name": "Splat Rotations",
"description": "Fetch the current and upcoming Splatoon rotations without SplatNet log in",
"version": "1.0",
"icons": {
"16": "images/icon16.png",
"19": "images/icon19.png",
"32": "images/icon32.png",
"38": "images/icon38.png",
"48": "images/icon48.png",
"128": "images/icon128.png"
},
"browser_action": {
"default_title": "Splat Rotations",
"default_icon": {
"16": "images/icon16.png",
"19": "images/icon19.png",
"32": "images/icon32.png",
"38": "images/icon38.png",
"48": "images/icon48.png",
"128": "images/icon128.png"
},
"default_popup": "popup.html"
},
"permissions": [
"https://splatoon.ink/"
]
}
popup.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Splat Rotations</title>
<link rel="stylesheet" href="popup.css">
</head>
<body>
<div id="rotations"></div>
<footer></footer>
<script src="popup.js"></script>
</body>
</html>
popup.js
// Get Splatoon map rotations using the Splatoon.ink API
function retrieveRotations() {
// Retrieve JSON file
var AJAX_req = new XMLHttpRequest();
AJAX_req.open("GET", 'https://splatoon.ink/schedule.json', true);
AJAX_req.setRequestHeader("Content-type", "application/json");
AJAX_req.onreadystatechange = function() {
// Check if splatoon.ink is up and running
if(AJAX_req.readyState == 4 && AJAX_req.status == 200) {
// Parse JSON
var json = JSON.parse(AJAX_req.responseText)
parseRotations(json);
}
}
AJAX_req.send(null);
}
// Parse acquired data
function parseRotations(data) {
////
//// This is just parsing the JSON and adding divs with the data to the DOM.
////
}
window.addEventListener('load', function() {
retrieveRotations();
}, false);
我可以添加一个按钮和一个单击事件监听器,但这需要用户执行两个操作(单击扩展按钮,然后单击另一个刷新按钮),但我真的不想这样做。 / p>
答案 0 :(得分:1)
这可能是一个缓存问题,因此我使用URL参数将当前时间戳附加到JSON,因此JSON永远不会相同。
var noCacheJSON = new Date().getTime();
AJAX_req.open("GET", 'https://url.json?c='+noCacheJSON, true);
它终于正常工作了!
答案 1 :(得分:-1)
让您的popup.js
文件包含:
document.addEventListener('DOMContentLoaded', function() {
retrieveRotations();
//Other Actions
}
答案 2 :(得分:-1)
“我希望每次用户点击按钮扩展时,扩展程序都会更新JSON和DOM。”您需要在background.js文件中使用chrome.browserAction API来检测扩展图标上的点击。根据chrome.browserAction docs,此代码如下所示:
chrome.browserAction.onClicked.addListener(function(tab) {
//Execute your content script here...
chrome.tabs.executeScript({ file: "popup.js" });
});
如需进一步参考,请查看Google的Chrome扩展程序examples。标题为“点击时更改其图标的浏览器操作”的示例还将显示如何处理单击扩展图标。