Skip to content

Commit

Permalink
Use plugins_url() to allow Workbox script URLs to be filtered
Browse files Browse the repository at this point in the history
  • Loading branch information
westonruter committed Aug 24, 2021
1 parent d7e2dea commit 8f87703
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,9 @@ public function get_priority() {
* @return string Script.
*/
public function get_script() {
$current_scope = wp_service_workers()->get_current_scope();
$workbox_dir = sprintf( 'wp-includes/js/workbox-v%s/', PWA_WORKBOX_VERSION );
$current_scope = wp_service_workers()->get_current_scope();
$workbox_dir_path = sprintf( 'wp-includes/js/workbox-v%s/', PWA_WORKBOX_VERSION );
$workbox_dir_url = plugins_url( $workbox_dir_path, PWA_PLUGIN_FILE );

$script = '';
if ( SCRIPT_DEBUG ) {
Expand All @@ -64,17 +65,17 @@ public function get_script() {
// Load with importScripts() so that source map is available.
$script .= sprintf(
"importScripts( %s );\n",
wp_json_encode( PWA_PLUGIN_URL . $workbox_dir . 'workbox-sw.js' )
wp_json_encode( $workbox_dir_url . 'workbox-sw.js' )
);
} else {
// Inline the workbox-sw.js to avoid an additional HTTP request.
$wbjs = file_get_contents( PWA_PLUGIN_DIR . '/' . $workbox_dir . 'workbox-sw.js' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
$wbjs = file_get_contents( PWA_PLUGIN_DIR . '/' . $workbox_dir_path . 'workbox-sw.js' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
$script .= preg_replace( '://# sourceMappingURL=.+?\.map\s*$:s', '', $wbjs );
}

$options = array(
'debug' => SCRIPT_DEBUG, // When true, the dev builds are loaded. Otherwise, the prod builds are used.
'modulePathPrefix' => PWA_PLUGIN_URL . $workbox_dir,
'modulePathPrefix' => $workbox_dir_url,
);
$script .= sprintf( "workbox.setConfig( %s );\n", wp_json_encode( $options ) );

Expand Down
12 changes: 7 additions & 5 deletions wp-includes/service-workers.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,11 +167,13 @@ function wp_print_service_workers() {
return;
}

$workbox_window_src = sprintf(
'%s/wp-includes/js/workbox-v%s/workbox-window.%s.js',
PWA_PLUGIN_URL,
PWA_WORKBOX_VERSION,
SCRIPT_DEBUG ? 'dev' : 'prod'
$workbox_window_src = plugins_url(
sprintf(
'wp-includes/js/workbox-v%s/workbox-window.%s.js',
PWA_WORKBOX_VERSION,
SCRIPT_DEBUG ? 'dev' : 'prod'
),
PWA_PLUGIN_FILE
);
$register_options = array(
'scope' => $scope,
Expand Down

0 comments on commit 8f87703

Please sign in to comment.