Original link: https://immmmm.com/randompost-by-sitemap/
See both @HEO and @Leonus have posted on this topic. After trying it out, the latter method is adopted, which is straightforward and simple. Tap the menu’s ? icon to experience it.
The specific implementation idea is to directly parse the sitemap.xml at the front end, obtain a url loc
link randomly, and add judgment at the same time. If you accidentally get the following links (home page, tab page, category page, etc., use .split('/')[3]
Take the characters after the main domain name/ as the judgment basis), then recycle to take one.
< loc >https://immmmm.com/</ loc > < loc >https://immmmm.com/tags/</ loc >
Relevant JavaScript code:
function randomPost () { fetch ( '/sitemap.xml' ). then ( res => res . text ()). then ( str => ( new window. DOMParser ()). parseFromString ( str , "text/xml" )). then ( data => { let ls = data . querySelectorAll ( 'url loc' ); let locationHref , locSplit ; do { locationHref = ls [Math. floor (Math. random () * ls . length )]. innerHTML locSplit = locationHref . split ( '/' )[ 3 ] || '' } while ( locSplit == '' || locSplit == 'tags' ); //若所有文章都如https://…….com/posts/2022/07/…… 格式,主域名后字符是posts,则循环条件改为: //while (locSplit !== 'posts'); location . href = locationHref }) }
Of course, if all articles are in the format of https://…….com/posts/2022/07/……
and the character after the main domain name is posts
, then the loop condition will be changed to: while (locSplit !== 'posts');
Find another place to drop the html code:
< a href = "javascript:;" onclick = "randomPost()" title = "随机访问一篇文章" >随机</ a >
This article is reprinted from: https://immmmm.com/randompost-by-sitemap/
This site is for inclusion only, and the copyright belongs to the original author.