SilentVoid13 / Templater

A template plugin for obsidian
https://silentvoid13.github.io/Templater
GNU Affero General Public License v3.0
3.25k stars 194 forks source link

Add functionality for Nasa APOD #712

Closed base-I closed 2 years ago

base-I commented 2 years ago

Would it be possible to have a functionality like _tp.web.randompicture but for https://apod.nasa.gov/ ?

This would be very nice - thank you :)

welpdx commented 2 years ago

Ok took me a bit but here's a script to do what you want. Here you go:

<%*
// Init
const baseurl = "https://apod.nasa.gov/apod/"
const url = baseurl + "astropix.html"
// request url
try{
var response = await tp.obsidian.request({url})
} catch (e) {
new Notice("Problem with url request.\n" + e)
console.log(e)
return;
}
if (response) {
    // Method 1. Regex. kind of clunky but works. 
    let findImg = new RegExp(`<IMG SRC=\"([^\"]+)`);
    var match = response.match(findImg);
    if (match) {
        const image_url = baseurl + match[1]
        tR+= `![tp.web.random_picture](${image_url})`
    } else {
    // try 2. find via querySelector
        var parser = new DOMParser();
        var htmlDoc = parser.parseFromString(response, 'text/html');
        var imgs = htmlDoc.body.getElementsByTagName("img")
        let test = htmlDoc.querySelector('[style="max-width:100%"]');
        const image_url = baseurl + test.getAttribute("src")
        tR+= `![tp.web.random_picture](${image_url})`
    }
} else {
    new Notice("No Reponse")
}
%>
Demo demo

I'm not good at making PRs but I will see.