如何解决Flutter Web:SPA:在元数据标签中使用URL参数
我想在URL中获取参数,并使用它们在我的SPA中生成og:image元标记。具体目的是为给定的URL提供动态缩略图。这个想法是使搜寻器能够找到合适的缩略图。
示例网址:
https://my.app/#/post?uid=abc&pid=123
这两个参数不一定总是包括在内。我希望它不会引起问题。 我的理解是,爬虫通常只检查html中的元数据。在元数据之前,如何在html中包含一些代码? (我对HTML比较陌生)
我可以将脚本放在head标签中吗?脚本之外的变量是否可用?我可以在og:image标签的URL地址中使用变量吗?
<!DOCTYPE html>
<html>
<head>
<meta property="og:image" content="https://my.app/{uid}/{pid}/thumb.png" />
<meta charset="UTF-8">
<meta content="IE=Edge" http-equiv="X-UA-Compatible">
<meta name="description" content="Get Dressed. Better than you ever had">
<!-- iOS meta tags & icons -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="vestiqweb">
<link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
<link rel="shortcut icon" type="image/png" href="favicon.png"/>
<title>VESTIQ</title>
<link rel="manifest" href="manifest.json">
</head>
<body id="app-container">
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load',function () {
navigator.serviceWorker.register('flutter_service_worker.js');
});
}
</script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.4/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.17.1/firebase-analytics.js"></script>
<script>
var firebaseConfig = {
//config info
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<script src="main.dart.js?version=14" type="application/javascript"></script>
</body>
</html>
解决方法
我能够在meta标记之前放置一个脚本,并使用window.location.href来获取URL。我使用URLSearchParams提取参数。但是,我只能得到第二个参数,而不能得到第一个。如果我在uid之前添加一个'&',它可以工作,但会使网址看起来很奇怪...“?&uid”
<script>
const queryString = window.location.href;
const urlParams = new URLSearchParams(queryString);
const uid = urlParams.get('uid')
const pid = urlParams.get('pid')
if (uid != null && pid != null)
document.getElementById('urlThumb').content = `https://my.app/posts%2F${uid}%2F${pid}%2Furl_thumb.jpg?alt=media`;
</script>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。