Path: blob/master/views/scram/scramjet.sw.js
5227 views
importScripts('{{route}}{{/scram/scramjet.all.js}}');1const { ScramjetServiceWorker } = $scramjetLoadWorker();2const scramjet = new ScramjetServiceWorker();34async function handleRequest(event) {5await scramjet.loadConfig();6if (scramjet.route(event)) {7return scramjet.fetch(event);8}9return fetch(event.request);10}1112self.addEventListener('fetch', (event) => {13event.respondWith(handleRequest(event));14});1516let playgroundData;17self.addEventListener('message', (event) => {18if (event.data.type === 'playgroundData') {19playgroundData = event.data;20} else if (event.data.type === 'requestAC') {21// Set up a message channel from common.js to process autocomplete search results.22const requestPort = event.ports[0];23requestPort.addEventListener('message', async (event) => {24const response = await scramjet.fetch(event.data);2526// This contains some duplicate code from common.js, since Response objects27// cannot be passed through service workers and must be preprocessed.28const responseType = response.headers.get('content-type');29let responseJSON = {};30if (responseType && responseType.indexOf('application/json') !== -1)31responseJSON = await response.json();32else33try {34responseJSON = await response.text();35try {36responseJSON = JSON.parse(responseJSON);37} catch (e) {38responseJSON = JSON.parse(39responseJSON.replace(/^[^[{]*|[^\]}]*$/g, '')40);41}42} catch (e) {43// responseJSON will be an empty object if everything was invalid.44}4546// Return the processed data.47requestPort.postMessage({48responseJSON: responseJSON,49searchType: event.data.type,50time: event.data.request.headers.get('Date'),51});52});53requestPort.start();54}55});565758