我正在开发React PWA,想知道是否可以动态地将图标URL添加到manifest.json
文件中。我的目标是在用户登录之前显示通用应用程序图标。随后,我从远程API请求一个新的图标并将其设置到清单文件中,以便更改收藏夹和控制台上的移动图标。
理想情况下,我希望能在不进行任何后端更改的情况下实现这一点。
我正在开发React PWA,想知道是否可以动态地将图标URL添加到manifest.json
文件中。我的目标是在用户登录之前显示通用应用程序图标。随后,我从远程API请求一个新的图标并将其设置到清单文件中,以便更改收藏夹和控制台上的移动图标。
理想情况下,我希望能在不进行任何后端更改的情况下实现这一点。
rel="manifest"
但没有href属性的链接标签。稍后使用此标签来填充您的清单。例如:
您的文档:<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>title</title>
<link rel="manifest" id="my-manifest-placeholder">
</head>
<body>
<!-- page content -->
</body>
</html>
在Javascript中你有两个选择:
使用URL设置href 属性:
document.querySelector('#my-manifest-placeholder').setAttribute('href', '/my-dynamic-manifest-url.json');
使用JSON对象来设置你的manifest
var myDynamicManifest = {
"name": "Your Great Site",
"short_name": "Site",
"description": "Something dynamic",
"start_url": "<your-url>",
"background_color": "#000000",
"theme_color": "#0f4a73",
"icons": [{
"src": "whatever.png",
"sizes": "256x256",
"type": "image/png"
}]
}
const stringManifest = JSON.stringify(myDynamicManifest);
const blob = new Blob([stringManifest], {type: 'application/json'});
const manifestURL = URL.createObjectURL(blob);
document.querySelector('#my-manifest-placeholder').setAttribute('href', manifestURL);
使用npm安装
npm install react-manifest
使用 yarn
yarn add react-manifest
在你的React组件中导入该包
import reactManifest from "react-manifest"
或者
const reactManifest = require("react-manifest")
在您的index.html文件中添加一个<link>
标签,将id
属性设置为"manifest-placeholder",将href
属性设置为"./manifest.json"
<link rel="manifest" id="manifest-placeholder" href="./manifest.json" />
在你的 React 组件中,创建一个对象并包含你想要在 manifest.json 文件中更新的细节内容。例如:
const manifestDetails = {
"name": "My Web App",
"short_name": "My App",
"start_url": "index.html",
"display": "standalone",
"orientation": "portrait",
"theme_color": "#000000",
"background_color": "#ffffff",
"icons": [
{
"src": "icon-192x192.png",
"sizes": "192x192"
},
{
"src": "icon-512x512.png",
"sizes": "512x512"
}
],
// And More...
}
使用update
方法通过传入清单细节和index.html文件中<link>
标签的ID来更新您的manifest.json文件。
reactManifest.update(manifestDetails, "#manifest-placeholder")
import React, { useEffect } from 'react';
import reactManifest from 'react-manifest';
const MyComponent = () => {
useEffect(() => {
const manifestDetails = {
"name": "My Web App",
"short_name": "My App",
"start_url": "index.html",
"display": "standalone",
"orientation": "portrait",
"theme_color": "#000000",
"background_color": "#ffffff",
"icons": [
{
"src": "icon-192x192.png",
"sizes": "192x192"
},
{
"src": "icon-512x512.png",
"sizes": "512x512"
}
],
And More...
};
reactManifest.update(manifestDetails, "#manifest-placeholder");
}, []);
return (
<div>
...
</div>
);
};
export default MyComponent;
<!DOCTYPE html>
<html>
<head>
<title>My Web App</title>
<link rel="manifest" id="manifest-placeholder" href="./manifest.json" />
</head>
<body>
<div id="root"></div>
<script src="./index.js"></script>
</body>
</html>