Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ function isIgnored(node, filter) {
* @returns {boolean | object} Error Object if the constrainsts are met or boolean otherwise
*/
function checkConnection(conn) {
// Check this before connection information, which is not available everywhere.
if (navigator.onLine === false) {
return new Error('offline');
}

// If no connection object, assume it's okay to prefetch
if (!conn) return true;

Expand Down
10 changes: 10 additions & 0 deletions test/fixtures/test-offline.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Prefetch: Offline</title>
</head>
<body>
<script src="../../dist/quicklink.umd.js"></script>
</body>
</html>
47 changes: 47 additions & 0 deletions test/quicklink.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -412,4 +412,51 @@ mainSuite('should consider threshold option before prefetching (UMD)', async con
assert.ok(responseURLs.includes(`${server}/4.html`));
});

for (const method of ['prefetch', 'prerender']) {
for (const hasConnection of [true, false]) {
mainSuite(`should reject ${method} offline with connection=${hasConnection}`, async context => {
await context.page.goto(`${server}/test-offline.html`);
await context.page.setOfflineMode(true);
try {
const result = await context.page.evaluate(async ({method, hasConnection}) => {
if (!hasConnection) {
Object.defineProperty(navigator, 'connection', {value: undefined});
}
let error;
try {
await quicklink[method]('/offline-target.html');
} catch (err) {
error = err.message;
}
return {
online: navigator.onLine,
error,
prefetches: document.querySelectorAll('link[rel="prefetch"]').length,
rules: document.querySelectorAll('script[type="speculationrules"]').length,
};
}, {method, hasConnection});
assert.is(result.online, false);
assert.is(result.error, `Cannot ${ method }, offline`);
assert.is(result.prefetches, 0);
assert.is(result.rules, 0);
} finally {
await context.page.setOfflineMode(false);
}
});
}
}

mainSuite('should allow prefetching the same URL after coming back online', async context => {
await context.page.goto(`${server}/test-offline.html`);
await context.page.setOfflineMode(true);
try {
await context.page.evaluate(() => quicklink.prefetch('1.html', true).catch(() => {}));
} finally {
await context.page.setOfflineMode(false);
}
const response = context.page.waitForResponse(`${server}/1.html`);
await context.page.evaluate(() => quicklink.prefetch('1.html', true));
assert.is((await response).status(), 200);
});

mainSuite.run();
Loading