如何在 PWA 和 ReactJS 中创建动态 manifest.json 文件?

IT技术 javascript reactjs react-redux
2021-04-20 07:09:14

我有一个项目需要为我的 PWA (ReactJS) 创建一个动态 manifest.json 文件。

请看下面我的代码:

app.service.js:

        function getAppDetails() {
            const requestOptions = {
                method: 'GET',
                headers: authHeader()
            };
            // TODO create dynamic manifest.json file here
            return fetch(`${config.apiUrl}/api/apps`, requestOptions).then(handleResponse);
        }   

        function handleResponse(response) {
            return response.text().then(text => {
                const data = text && JSON.parse(text);
                if (!response.ok) {
                    if (response.status === 401) {
                        // auto logout if 401 response returned from api
                        logout();
                        location.reload(true);
                    } 
                    const error = (data && data.message) || response.statusText;
                    return Promise.reject(error);
                }

                return data;
            });
}

app.actions.js:

function getAppDetails() {
        return dispatch => {
            dispatch(request());

            appService.getAppDetails()
                .then(
                    details => dispatch(success(details)),
                    error => dispatch(failure(error.toString()))
                );
        };

        function request() { return { type: appConstants.GETDETAILS_REQUEST } }
        function success(details) { return { type: appConstants.GETDETAILS_SUCCESS, details } }
        function failure(error) { return { type: appConstants.GETDETAILS_FAILURE, error } }
}

登录页面.jsx:

    import { appActions } from '../_actions';
    class LoginPage extends React.Component {
        constructor(props) {
            super(props);

            // reset login status
            this.props.dispatch(userActions.logout());

            this.state = {
                email: '',
                password: '',
                isDisabled: false,
                submitted: false
            };

            this.handleChange = this.handleChange.bind(this);
            this.handleSubmit = this.handleSubmit.bind(this);
            this.showSwal = this.showSwal.bind(this);
        }

        componentDidMount() {
            // TODO call the action to add dynamic manifest file to index.html
            this.props.dispatch(aapActions.getAppDetails());
        }

        render() {
            return (
                ................
            );
        }
}

我对这种事情很陌生。我该如何开始?

3个回答

如果您想创建动态 manifest.json,您希望在 HTML 中有一个带有 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>

使用 JSON 对象设置清单

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);

我遇到了 Blob 的一些问题,它在 android 中没有按预期工作。下面的答案工作正常。

 var myDynamicManifest = {
  "name": "Your Great Site",
  "short_name": "Site",
  "description": "Something dynamic",
  "start_url": "<your-url>",
  "background_color": "#000000",
  "theme_color": "#0f4a73",
  "icons": [
      {
        src: "icon_size_36.png",
        sizes: "36x36",
        type: "image/png",
      },
      {
        src: "icon_size_48.png",
        sizes: "48x48",
        type: "image/png",
      },
      {
        src: "icon_size_72.png",
        sizes: "72x72",
        type: "image/png",
      },
      {
        src: "icon_size_96.png",
        sizes: "96x96",
        type: "image/png",
      },
      {
        src: "icon_size_144.png",
        sizes: "144x144",
        type: "image/png",
      },
      {
        src: "icon_size_192.png",
        sizes: "192x192",
        type: "image/png",
      },
      {
        src: "icon_size_512.png",
        sizes: "512x512",
        type: "image/png",
      },
    ]
  }
  const link = document.createElement("link");
  link.rel = "manifest";    
  const stringManifest = JSON.stringify(myDynamicManifest);
  link.setAttribute('href', 'data:application/json;charset=utf-8,' + encodeURIComponent(stringManifest))
  document.head.appendChild(link);

灵感来自@Sanjeet kumar 为我的 NextJs 应用程序提供的解决方案:

// _document.tsx
<link href="/manifest.json" rel="manifest" id="manifest" />


// _app.tsx
import manifest from "../../public/manifest.json";

const manifestElement = document.getElementById("manifest");
const manifestString = JSON.stringify({
  ...manifest,
  start_url: `${homePagePath}${storeCode}`,
});
manifestElement?.setAttribute(
  "href",
  "data:application/json;charset=utf-8," + encodeURIComponent(manifestString)
);
使用这种方法给了我 Manifest: property 'start_url' ignored, URL is invalid.
2021-06-15 07:09:14