seance/static/bookmarklet.js

78 lines
2.2 KiB
JavaScript
Raw Permalink Normal View History

(() => {
const baseUrl = document.querySelector('[data-seance-url]').dataset.seanceUrl || 'http://localhost:4000'
function resetTitle() {
document.title = document.title.replace('[Loading...] ', '')
}
// Check that we're not on a Seance page
if (window.location.href.startsWith(baseUrl)) {
alert('That\'s not how to do it, silly!\n\nYou\'re supposed to BOOKMARK this link (by dragging it to the bookmarks bar or right-clicking and saying "save bookmark").\n\nWait till you\'re on a Medium page; don\'t try to start clicking on it right now ;)')
// Reset title
resetTitle()
return
}
// Keep the user engaged with a nice bannery message
var d1 = document.createElement('div')
d1.style="position: absolute; top:0; right: 0; left: 0; background-color: turquoise; min-height: 2em; z-index: 1000; text-align: center;"
var p1 = document.createElement('p')
p1.innerHTML = 'Seance loading in progress...'
p1.style='font-size: 2rem; margin: 2rem; color: white;'
d1.appendChild(p1)
document.body.appendChild(d1)
// Form sending function
function handleJSON(data) {
try {
data = JSON.parse(data.slice(data.indexOf('{')))
} catch (err) {
alert('Something went wrong fetching the post. Please make sure you\'re on a Medium site and try again.')
// Hide the loading screen
d1.parentElement.removeChild(d1)
// Reset the title
resetTitle()
// Give up
return
}
// Create a form to hold the data
var f = document.createElement('form')
f.action=baseUrl + '/fetch/'
f.method='post'
// Create hidden input to hold data
i = document.createElement('input')
i.name='data'
i.type='hidden'
i.value=JSON.stringify(data)
// Assign children to parents
f.appendChild(i)
document.body.appendChild(f)
// Submit the form
f.submit()
}
// fetch the XML
var r = new XMLHttpRequest()
r.open('GET', window.location + '?format=json')
r.onreadystatechange = function () {
if (r.readyState == 4 && r.status == 200) {
handleJSON(r.responseText)
}
}
r.setRequestHeader("Content-Type", "application/json;charset=utf-8")
r.send(null)
})()