// ==UserScript==
// @name 新闻速递
// @namespace Violentmonkey Scripts
// @match *://*/*
// @grant GM_xmlhttpRequest
// @grant GM_openInTab
// @grant GM_registerMenuCommand
// @version 1.5
// @description Fetch news from API and open in a new tab with responsive design and translation.
// @run-at document-end
// @downloadURL https://update.greasyfork.icu/scripts/518571/%E6%96%B0%E9%97%BB%E9%80%9F%E9%80%92.user.js
// @updateURL https://update.greasyfork.icu/scripts/518571/%E6%96%B0%E9%97%BB%E9%80%9F%E9%80%92.meta.js
// ==/UserScript==
(function() {
'use strict';
const apiKey = 'dac6abc0634b4de08429b2580628dba8';
const apiUrl = `https://newsapi.org/v2/top-headlines?country=us&apiKey=${apiKey}`;
// Function to fetch and display news
function fetchAndDisplayNews() {
GM_xmlhttpRequest({
method: "GET",
url: apiUrl,
onload: function(response) {
if (response.status === 200) {
const data = JSON.parse(response.responseText);
if (data.articles && data.articles.length > 0) {
let newsContent = `
新闻列表
Latest News
`;
const translatePromises = data.articles.map(async (article) => {
const translatedTitle = await translateText(article.title, 'en', 'zh-CN');
const translatedDescription = article.description ? await translateText(article.description, 'en', 'zh-CN') : 'No translation available.';
return { ...article, translatedTitle, translatedDescription };
});
Promise.all(translatePromises).then((translatedArticles) => {
translatedArticles.forEach(article => {
newsContent += `
-
${article.title}
${article.translatedTitle}
${article.description || 'No description available.'}
${article.translatedDescription}
`;
});
newsContent += `
`;
GM_openInTab(`data:text/html;charset=utf-8,${encodeURIComponent(newsContent)}`, { active: true });
});
} else {
alert('No news found.');
}
} else {
alert('Failed to fetch news. Status: ' + response.status);
}
},
onerror: function(error) {
console.error("Error fetching news:", error);
alert('An error occurred while fetching news.');
}
});
}
async function translateText(text, sourceLang, targetLang) {
if (!text) {
return '';
}
const encodedText = encodeURIComponent(text);
const url = `https://translate.googleapis.com/translate_a/single?client=gtx&sl=${sourceLang}&tl=${targetLang}&dt=t&q=${encodedText}`;
try {
const response = await fetch(url);
if (!response.ok) {
console.error("Translation API failed:", response.status);
return 'Translation failed.';
}
const data = await response.json();
return data[0][0][0];
} catch (error) {
console.error("Error during translation:", error);
return 'Translation failed.';
}
}
// Register the menu command
GM_registerMenuCommand("Fetch Latest News", fetchAndDisplayNews);
})();