Generieren eines zufälligen Britannica-ArtikelsJavaScript

Javascript-Forum
Anonymous
 Generieren eines zufälligen Britannica-Artikels

Post by Anonymous »

Ich habe versucht, einen funktionierenden Javascript-Code zu bekommen, der einen zufälligen Artikel von britannica.com generieren würde. Hier ist die Logik, die ich implementieren möchte: Ich habe versucht:
(1) Bookmarklet (2) Tampermonkey-Skript (3) HTML-Seite.
Aus irgendeinem Grund nichts davon hat funktioniert. Laut chatgpt liegt es an der Browsersicherheit.
Ich habe mich gefragt, ob es dabei tatsächlich einige Einschränkungen gibt? Was ist der empfohlene Weg, dies zu tun (d. h. ich möchte einen Javascript-Code ausführen, der eine zufällige Seite von Britannica berechnet und dorthin weitergeleitet wird)? Kann das in Javascript gemacht werden oder liegt hier ein Sicherheitsproblem vor?
Update: Hier ist der Code, der nicht funktioniert hat (Haftungsausschluss: Ich habe ihn mit grok generiert):
(1) bookmarklet
Unten ist der Code, der tatsächlich funktioniert hat. Das Problem dabei ist, dass die Anzahl der Artikel fest codiert ist (d. h. wenn ich dies als speichere). Wenn ich ein Lesezeichen anlege und es öffne, werde ich tatsächlich zu einem Artikel weitergeleitet)

Code: Select all

javascript:(async function(){const cats=['0-9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];const weights=[20,80,60,70,50,60,40,40,50,40,20,30,40,50,40,50,50,15,50,90,60,30,20,20,10,10,10];let total=weights.reduce((a,b)=>a+b,0);let r=Math.random()*total;let sum=0;let cat;for(let i=0;i parseInt(a.getAttribute('href').match(/\/(\\d+)$/)[1])).filter(n => !isNaN(n));
const maxPage = Math.max(...pageNums);
if (maxPage < 1) { window.location.href = 'https://www.britannica.com'; return; }
const randomPage = Math.floor(Math.random() * maxPage) + 1;
const listUrl = \`https://www.britannica.com/sitemap/\${cat}/\${randomPage}\`;

GM_xmlhttpRequest({
method: "GET",
url: listUrl,
onload: function(resp) {
if (resp.status !== 200) { window.location.href = 'https://www.britannica.com'; return; }
const doc2 = parser.parseFromString(resp.responseText, 'text/html');
const links = Array.from(doc2.querySelectorAll('a[href^="/"]')).filter(a => {
const h = a.getAttribute('href');
return h && (
/^\/(biography|topic|animal|plant|sports|technology|art|geography|place|science|money|video|story|gallery)\//.test(h) ||
/\/[^\/]+-\d+$/.test(h)
);
});
if (links.length === 0) { window.location.href = 'https://www.britannica.com'; return; }
const randomLink = links[Math.floor(Math.random() * links.length)];
window.location.href = 'https://www.britannica.com' + randomLink.getAttribute('href');
}
});
}
});
}.toString()})();`;document.body.appendChild(script);script.remove();})();


(2)
Für Tampermonkey schien das folgende Skript das zu tun, was ich wollte, tat es aber einfach in einer Endlosschleife ohne Unterbrechung.

Code: Select all

// ==UserScript==
// @name         Random Britannica Launcher
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Menu launcher for the main random Britannica script
// @author       You
// @match        *://*/*
// @grant        GM_registerMenuCommand
// ==/UserScript==

(function() {
'use strict';
GM_registerMenuCommand("Random Britannica Article", function() {
// Paste the entire main script code here as a string and eval it
eval(`const cats = ['0-9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
const cat = cats[Math.floor(Math.random() * cats.length)];
const indexUrl = \`https://www.britannica.com/sitemap/\${cat}\`;

GM_xmlhttpRequest({
method: "GET",
url: indexUrl,
onload: function(response) {
if (response.status !== 200) { window.location.href = 'https://www.britannica.com'; return; }
const parser = new DOMParser();
const doc = parser.parseFromString(response.responseText, 'text/html');
const pageLinks = Array.from(doc.querySelectorAll(\`a[href^="/sitemap/\${cat}/"]\`));
if (pageLinks.length === 0) { window.location.href = 'https://www.britannica.com'; return; }
const pageNums = pageLinks.map(a => parseInt(a.getAttribute('href').match(/\/(\\\\d+)$/)[1])).filter(n =>  !isNaN(n));
const maxPage = Math.max(...pageNums);
if (maxPage < 1) { window.location.href = 'https://www.britannica.com'; return; }
const randomPage = Math.floor(Math.random() * maxPage) + 1;
const listUrl = \`https://www.britannica.com/sitemap/\${cat}/\${randomPage}\`;

GM_xmlhttpRequest({
method: "GET",
url: listUrl,
onload: function(resp) {
if (resp.status !== 200) { window.location.href = 'https://www.britannica.com'; return; }
const doc2 = parser.parseFromString(resp.responseText, 'text/html');
const links = Array.from(doc2.querySelectorAll('a[href^="/"]')).filter(a => {
const h = a.getAttribute('href');
return h && (
/^\/(biography|topic|animal|plant|sports|technology|art|geography|place|science|money|video|story|gallery)\//.test(h) ||
/\/[^\/]+-\\d+$/.test(h)
);
});
if (links.length === 0) { window.location.href = 'https://www.britannica.com'; return; }
const randomLink = links[Math.floor(Math.random() * links.length)];
window.location.href = 'https://www.britannica.com' + randomLink.getAttribute('href');
}
});
}
});`);
});
})();


Dann eine andere Version, die ich überhaupt nicht ausführen konnte (in dem Sinne, dass ich nicht einmal sicher war, wie ich Tampermonkey dazu bringen sollte, sie auszuführen)

Code: Select all

// ==UserScript==
// @name         Random Britannica Article (Perfect Fixed)
// @namespace    http://tampermonkey.net/
// @version      4.0
// @description  Menu-only one-click true random Britannica article - dynamic, no loops, works every time
// @author       You + Grok
// @match        *://*/*
// @grant        GM_xmlhttpRequest
// @grant        GM_registerMenuCommand
// ==/UserScript==

GM_registerMenuCommand("Get Random Britannica Article", function() {
'use strict';
const cats = ['0-9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
const cat = cats[Math.floor(Math.random() * cats.length)];
const indexUrl = `https://www.britannica.com/sitemap/${cat}`;

GM_xmlhttpRequest({
method: "GET",
url: indexUrl,
onload: function(response) {
if (response.status !== 200) {
window.location.href = 'https://www.britannica.com';
return;
}
const text = response.responseText;

// Regex to catch all (/sitemap/cat/number) paths
const pageMatches = [...text.matchAll(/\/sitemap\/[^\/]+\/(\d+)/g)];
if (pageMatches.length === 0) {
window.location.href = 'https://www.britannica.com';
return;
}

const pageNums = pageMatches.map(m => parseInt(m[1]));
const maxPage = Math.max(...pageNums);

const randomPage = Math.floor(Math.random() * maxPage) + 1;
const listUrl = `https://www.britannica.com/sitemap/${cat}/${randomPage}`;

GM_xmlhttpRequest({
method: "GET",
url: listUrl,
onload: function(resp) {
if (resp.status !== 200) {
window.location.href = 'https://www.britannica.com';
return;
}
const parser = new DOMParser();
const doc2 = parser.parseFromString(resp.responseText, 'text/html');

const links = Array.from(doc2.querySelectorAll('a[href^="/"]')).filter(a => {
const h = a.getAttribute('href');
return h &&  (
/^\/(biography|topic|animal|plant|sports|technology|art|geography|place|science|money|video|story|gallery)\//.test(h) ||
/\/[^\/]+-\d+$/.test(h)
);
});

if (links.length === 0) {
window.location.href = 'https://www.britannica.com';
return;
}

const randomLink = links[Math.floor(Math.random() * links.length)];
window.location.href = 'https://www.britannica.com' + randomLink.getAttribute('href');
},
onerror: function() {
window.location.href = 'https://www.britannica.com';
}
});
},
onerror: function() {
window.location.href = 'https://www.britannica.com';
}
});
});


(3) Für HTML habe ich eine lokale .html-Datei gespeichert und sie in Chrome geöffnet. Es hat mich gerade auf die gleiche Seite britannica.com weitergeleitet

Code: Select all




Random Britannica

(async function() {
const cats = ['0-9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
const cat = cats[Math.floor(Math.random() * cats.length)];
const indexUrl = `https://www.britannica.com/sitemap/${cat}`;

try {
const resp = await fetch(indexUrl);
if (!resp.ok) throw '';
const text = await resp.text();

// Extract all page numbers from raw text (handles their Markdown links)
const matches = [...text.matchAll(/\/sitemap\/[^\/]+\/(\d+)/g)];
if (matches.length === 0) throw '';

const pageNums = matches.map(m => parseInt(m[1]));
const maxPage = Math.max(...pageNums);

const randomPage = Math.floor(Math.random() * maxPage) + 1;
const listUrl = `https://www.britannica.com/sitemap/${cat}/${randomPage}`;

const resp2 = await fetch(listUrl);
if (!resp2.ok) throw '';
const text2 = await resp2.text();

const parser = new DOMParser();
const doc = parser.parseFromString(text2, 'text/html');

const links = Array.from(doc.querySelectorAll('a[href^="/"]')).filter(a => {
const h = a.getAttribute('href');
return h && (
/^\/(biography|topic|animal|plant|sports|technology|art|geography|place|science|money|video|story|gallery)\//.test(h) ||
/\/[^\/]+-\d+$/.test(h)
);
});

if (links.length === 0) throw '';

const randomLink = links[Math.floor(Math.random() * links.length)];
window.location.href = 'https://www.britannica.com' + randomLink.getAttribute('href');

} catch (e) {
// Rare failure fallback
window.location.href = 'https://www.britannica.com';
}
})();



Loading your random Britannica article...



Entschuldigung im Voraus, falls dies etwas Offensichtliches für Experten ist. Wie ich bereits erwähnt habe, wollte ich dies eher als Metafrage bezüglich der Einschränkungen der Tools verstehen, die ich hier verwenden möchte.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post