mirror of
https://github.com/terribleplan/next.js.git
synced 2024-01-19 02:48:18 +00:00
48e4c771c2
In my use case, the client pings are failing since the requests do not send basic auth credentials right now. This change was made in https://github.com/zeit/next.js/pull/2509 I am not sure why it was undone as a part of https://github.com/zeit/next.js/pull/3578 Can someone explain why? Thanks.
61 lines
1.5 KiB
JavaScript
61 lines
1.5 KiB
JavaScript
/* global location */
|
|
|
|
import Router from '../lib/router'
|
|
import fetch from 'unfetch'
|
|
|
|
export default ({assetPrefix}) => {
|
|
Router.ready(() => {
|
|
Router.events.on('routeChangeComplete', ping)
|
|
})
|
|
|
|
async function ping () {
|
|
try {
|
|
const url = `${assetPrefix || ''}/_next/on-demand-entries-ping?page=${Router.pathname}`
|
|
const res = await fetch(url, {
|
|
credentials: 'same-origin'
|
|
})
|
|
const payload = await res.json()
|
|
if (payload.invalid) {
|
|
// Payload can be invalid even if the page is not exists.
|
|
// So, we need to make sure it's exists before reloading.
|
|
const pageRes = await fetch(location.href, {
|
|
credentials: 'same-origin'
|
|
})
|
|
if (pageRes.status === 200) {
|
|
location.reload()
|
|
}
|
|
}
|
|
} catch (err) {
|
|
console.error(`Error with on-demand-entries-ping: ${err.message}`)
|
|
}
|
|
}
|
|
|
|
let pingerTimeout
|
|
async function runPinger () {
|
|
// Will restart on the visibilitychange API below. For older browsers, this
|
|
// will always be true and will always run, but support is fairly prevalent
|
|
// at this point.
|
|
while (!document.hidden) {
|
|
await ping()
|
|
await new Promise((resolve) => {
|
|
pingerTimeout = setTimeout(resolve, 5000)
|
|
})
|
|
}
|
|
}
|
|
|
|
document.addEventListener('visibilitychange', () => {
|
|
if (!document.hidden) {
|
|
runPinger()
|
|
} else {
|
|
clearTimeout(pingerTimeout)
|
|
}
|
|
}, false)
|
|
|
|
setTimeout(() => {
|
|
runPinger()
|
|
.catch((err) => {
|
|
console.error(err)
|
|
})
|
|
}, 10000)
|
|
}
|