如何在SvelteKit中获得用户代理加载功能



我想在load function上获取user agent,以根据访问者是否为googlebot来选择是否执行服务器端渲染。

如何在load function中访问它?

我使用的是SvelteKit的最新版本,它是1.0.0。

使用钩子管理它。

src文件夹中创建hooks.js

export function getSession(request) {
return {
userAgent: request.headers['user-agent']
}
}

然后你可以在你想要的每个组件的load function中使用它:

<script context="module">
export async function load({ session }) {
console.log(session.userAgent)
}
</script>

有关文档中的更多信息,请参阅hooks部分。

还不允许发表评论,但加载({request}(对我有效:

/** @type {import('./$types').PageLoad} */
export async function load({ request }) {
const headers = request.headers;
const userAgent = headers.get('user-agent');
console.log('User agent:', userAgent);
}

JSDoc导入使其字体友好,适用于Oliver Dixon

最新更新