Skip to content

Instantly share code, notes, and snippets.

@kasparsd
Last active February 20, 2024 12:17
Show Gist options
  • Save kasparsd/78284a46e886a8020dfb21615c269e86 to your computer and use it in GitHub Desktop.
Save kasparsd/78284a46e886a8020dfb21615c269e86 to your computer and use it in GitHub Desktop.
wp-admin-pwa.php
<?php
/**
* Plugin Name: Admin PWA
*/
namespace Preseto\Admin_PWA;
const ACTION_QUERY_VAR = 'admin-pwa';
function manifest_url() {
return admin_url( '/wp-admin.manifest' );
}
function service_worker_url() {
return admin_url( '/wp-admin.service-worker', __FILE__ );
}
add_action(
'admin_head',
function () {
printf(
'<link rel="manifest" href="%s" />',
esc_attr( manifest_url() )
);
printf(
'<script>if ( "serviceWorker" in navigator ) { navigator.serviceWorker.register( "%s" ); }</script>',
service_worker_url()
);
}
);
// Remember to flush the rewrite rules by visiting the permalinks settings page.
add_action(
'init',
function () {
add_rewrite_rule(
sprintf( '^%s$', preg_quote( ltrim( wp_parse_url( manifest_url(), PHP_URL_PATH ), '/' ), '/' ) ),
sprintf( 'index.php?%s=manifest', ACTION_QUERY_VAR )
);
add_rewrite_rule(
sprintf( '^%s$', preg_quote( ltrim( wp_parse_url( service_worker_url(), PHP_URL_PATH ), '/' ), '/' ) ),
sprintf( 'index.php?%s=service-worker', ACTION_QUERY_VAR )
);
}
);
add_filter(
'query_vars',
function ( $query_vars ) {
$query_vars[] = ACTION_QUERY_VAR;
return $query_vars;
}
);
add_action(
'template_redirect',
function () {
$action = get_query_var( ACTION_QUERY_VAR );
if ( 'manifest' === $action ) {
wp_send_json(
[
'display' => 'standalone',
'theme_color' => '#363b3f', // Match the admin bar background.
'background_color' => '#f1f1f1', // Match the admin body background.
'name' => html_entity_decode( get_bloginfo( 'name' ) ),
'short_name' => html_entity_decode( get_bloginfo( 'name' ) ),
'description' => html_entity_decode( get_bloginfo( 'description' ) ),
'start_url' => admin_url( 'index.php' ),
'icons' => [
[
'src' => admin_url( '/images/wordpress-logo-white.svg' ),
'sizes' => 'any',
'type' => 'image/svg+xml',
'purpose' => 'any'
],
],
]
);
} elseif ( 'service-worker' === $action ) {
header( 'Content-Type: text/javascript' );
echo file_get_contents( __DIR__ . '/service-worker.js' );
exit;
}
}
);
const CACHE_NAME = "wp-admin-v1";
const ASSETS_TO_CACHE = [
'/wp-admin/',
'/wp-admin/index.php',
];
self.addEventListener(
'install',
( event ) => {
event.waitUntil(
caches.open( CACHE_NAME )
.then( ( cache ) => cache.addAll( ASSETS_TO_CACHE ) )
.catch( console.warn )
);
}
);
self.addEventListener(
'activate',
( event ) => {
// TODO: Delete entries with keys different from the current revision.
}
);
self.addEventListener(
'fetch',
( event ) => {
// TODO: Respond with cached entries if offline.
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment