Flutter Web: SPA: Open Graph: 动态分配og:image元标记

4
尝试创建动态og:image标签以便爬虫捕捉到适当的缩略图。 我有一个JS脚本可以生成适当的og:image URL,但是爬虫似乎在搜索时不运行任何JS。 有更好的方法吗?
<head>
  <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>
  <meta property="og:image" id='urlThumb' content="https://my.app/default%default.png?alt=media"/>

...

</head>
2个回答

2

好的,所以我能够以一种半黑客的方式实现这个。我修改了firebase.json文件,将'/post'路由重定向到一个firebase云函数。你只需要添加你想要重定向的“源”路由,并添加你想要触发的firebase云函数的名称。

    "rewrites": [
      {
        "source": "/post",
        "function": "prebuildPostPage"
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]

我需要添加“express”包来处理https请求。在你的函数文件夹中运行“npm i express”。然后我创建了这两个函数(看起来有点奇怪):

const express = require('express');
const app = express();

app.get('/post', (req, res) => {
    console.log(req.query);
    const uid = req.query.uid;
    const pid = req.query.pid;
    console.log(`uid[${uid}], pid[${pid}]`);
    if (uid == null || pid == null)
        res.status(404).send("Post doesn't exist");
    res.send(`<!DOCTYPE html>
    <html>
    <head>
      <meta property="og:image" id='urlThumb' content="${`https://my.app/posts%2F${uid}%2F${pid}%2Furl_thumb.jpg?alt=media`}"/>
      <meta property="og:image:width" content="800">
      <meta property="og:image:height" content="600">
      
      //Rest is the same as index.js head.

    </head>
    <body id="app-container">
      //Same as index.js body
    </body>
    </html>
    `);
});

exports.prebuildPostPage = functions.https.onRequest(app);

这对于向网络爬虫提供正确的缩略图非常有效,但不幸的是,它会将人们发送到主页。不好。

这是因为Flutter Web使用“#”来管理页面路由和历史记录。在转发到我的云函数的URL中,忽略了哈希标记后的所有内容。

所以...这是一个hack方法...在我的flutter web应用程序main.dart文件中,我必须检查给定的URL是否实际上是“my.app/post?uid=xxx&pid=xxx”格式。如果是这种情况,我创建了第二个选项MyAppPost,而不是加载默认的MyApp(从主页开始),该选项默认为带有提供的uid和pid数据的帖子屏幕。这起作用了,但它破坏了我的导航系统。

将继续尝试改进此设置。

void main() {
  //Provider.debugCheckInvalidValueType = null;
  setupLocator();
  String url = window.location.href;
  String _uid;
  String _pid;
  bool isPost = false;
  print(url);
  if (url.contains('/post')) {
    _uid = getParam(url, 'uid', 28);
    _pid = getParam(url, 'pid', 20);
    if (_uid != null && _pid != null) isPost = true;
  }
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (_) => PageManager(),
        ),
      ],
      child: isPost
          ? MyAppPost(
              uid: _uid,
              pid: _pid,
            )
          : MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'VESTIQ',
      navigatorKey: locator<NavigationService>().navigatorKey,
      onGenerateRoute: (rs) => generateRoute(rs, context),
      initialRoute: HomeRoute,
    );
  }
}

class MyAppPost extends StatelessWidget {
  final String uid;
  final String pid;

  const MyAppPost({Key key, this.uid, this.pid}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'VESTIQ',
      navigatorKey: locator<NavigationService>().navigatorKey,
      //onGenerateRoute: (rs) => generateRoute(rs, context),
      home: PostView(
        oid: uid,
        pid: pid,
      ),
    );
  }
}

编辑:正在工作的导航器

void main() {
  setupLocator();
  String url = window.location.href;
  String _uid;
  String _pid;
  bool launchWebApp = false;
  if (url.contains('/post')) {
    _uid = getParam(url, 'uid', 28);
    _pid = getParam(url, 'pid', 20);
  }
  if (url.contains('/app')) launchWebApp = true;
  runApp(
    MyApp(
      uid: _uid,
      pid: _pid,
      launchWebApp: launchWebApp,
    ),
  );
}

class MyApp extends StatelessWidget {
  final String uid;
  final String pid;
  final bool launchWebApp;

  const MyApp({Key key, this.uid, this.pid, this.launchWebApp})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    bool isPostLink = (uid != null && pid != null);
    if (isPostLink) {
      urlPost = PostCard.fromPost(Post()
        ..updatePost(
          uid: uid,
          pid: pid,
        ));
    }
    Provider.of<Post>(context, listen: false).updatePost(uid: uid, pid: pid);
    return MaterialApp(
      title: 'VESTIQ',
      navigatorKey: locator<NavigationService>().navigatorKey,
      onGenerateRoute: (rs) => generateRoute(rs, context),
      initialRoute: launchWebApp
          ? AppRoute
          : isPostLink
              ? PostRoute
              : HomeRoute,
    );
  }
}

请保持更新,我正在关注这个问题,因为我也遇到了同样的问题。 - baselsader
1
导航系统最终确实能够工作。但是URL有点丑陋。它变成了“my.app/post?uid=xxx&pid=xxx/#/[navigator page]”。也许有一种方法可以修改现有的URL,但我还没有这个需求。我只是在构建MVP。这仍然是我正在使用的解决方案。 - Maksym Moros
1
非常感谢您的更新!我会尝试并看看它会带我去哪里。 - baselsader

0

由于我没有使用 Firebase Blaze 计划,所以无法使用云函数。我不得不使用动态链接为每篇文章生成特定的链接。这些链接在 Facebook 上分享时,可以按照我想要的方式呈现网页和移动端的图片。

static Future<String> createDynamicLink(Feed feed) async {
String uriPrefix = "https://desigag.in/sharelink";
String deepLink = GlobalUtil.buildFeedUrl(feed.id);
String package = 'your package name';
String description='';

if(feed!=null){
  description = feed.totalComments.toString()+' Comments ■ '+ feed.totalHits.toString()+ ' Points';
}

if(kIsWeb){

  String urlFinal = uriPrefix+'/?link='+deepLink+'&apn='+package+'&amv=0&st='+feed.content!+'&sd='+description+'&si='+feed.imageUrl!;
  var encodedContent  = Uri.encodeFull(urlFinal);
  return encodedContent;
}else{
  final DynamicLinkParameters parameters = DynamicLinkParameters(
    uriPrefix: uriPrefix,
    link:  Uri.parse(deepLink),
    androidParameters: const AndroidParameters(
      packageName: 'your package name',
      minimumVersion: 0,
    ),
    iosParameters: const IOSParameters(
      bundleId: 'your package name',
      minimumVersion: '0',
    ),
    socialMetaTagParameters: SocialMetaTagParameters(
        title: feed.content,
        description: description,
        imageUrl: Uri.parse(feed.fileType=='video'? feed.thumbUrl! :feed.imageUrls!)),

  );

  Uri url;
  final ShortDynamicLink shortLink =
  await FirebaseDynamicLinks.instance.buildShortLink(parameters);
  url = shortLink.shortUrl;
  return url.toString();
}

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接