Skip to content

Instantly share code, notes, and snippets.

@Aleix-Marti
Created February 2, 2024 07:52
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Aleix-Marti/91e54b03b23ed6b9458b746bd5c6841b to your computer and use it in GitHub Desktop.
PWA - Headless WP
// Para evitar problemas de CORS con las peticiones entre dominios distintos
add_action('init', 'handle_preflight');
function handle_preflight() {
$origin = get_http_origin();
if ($origin === 'https://midominio.com') {
header("Access-Control-Allow-Origin: midominio");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Headers: Origin, X-Requested-With, X-WP-Nonce, Content-Type, Accept, Authorization');
if ('OPTIONS' == $_SERVER['REQUEST_METHOD']) {
status_header(200);
exit();
}
}
}
add_filter('rest_authentication_errors', 'rest_filter_incoming_connections');
function rest_filter_incoming_connections($errors) {
$request_server = $_SERVER['REMOTE_ADDR'];
$origin = get_http_origin();
if ($origin !== 'https://midominio.com') return new WP_Error('forbidden_access', $origin, array(
'status' => 403
));
return $errors;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite App</title>
<script type="module" crossorigin src="/assets/script.js"></script>
<link rel="stylesheet" crossorigin href="/assets/style.css">
<link rel="manifest" href="manifest.json">
</head>
<body>
<div id="app"></div>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('service-worker.js')
.then(function(registration) {
console.log('Service Worker registrado con éxito:', registration);
})
.catch(function(error) {
console.log('Error al registrar el Service Worker:', error);
});
}
</script>
</body>
</html>
{
"name": "Dark Fantasy",
"short_name": "PWA",
"description": "Una aplicación web progresiva simple",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#000000",
"icons": [
{
"src": "icon.png",
"sizes": "192x192",
"type": "image/png"
}
]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment