Templater icon indicating copy to clipboard operation
Templater copied to clipboard

Add functionality for Nasa APOD

Open base-I opened this issue 1 year ago • 1 comments

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

This would be very nice - thank you :)

base-I avatar Aug 02 '22 23:08 base-I

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.

welpdx avatar Aug 04 '22 06:08 welpdx