我有一个网页,实现了一组选项卡每个显示不同的内容。单击选项卡不会刷新页面,而是隐藏/取消隐藏客户端的内容。
现在需要根据页面上选择的选项卡更改页面标题(出于SEO原因)。这可能吗?有人能建议一个解决方案,通过javascript动态改变页面标题,而不重新加载页面?
我有一个网页,实现了一组选项卡每个显示不同的内容。单击选项卡不会刷新页面,而是隐藏/取消隐藏客户端的内容。
现在需要根据页面上选择的选项卡更改页面标题(出于SEO原因)。这可能吗?有人能建议一个解决方案,通过javascript动态改变页面标题,而不重新加载页面?
当前回答
使用document.title。
请参阅本页的基本教程。
其他回答
使用document.title。它对大多数事情都很有用,但它会破坏你网站上的SEO。
例子:
document.write("title - " + document.title + "<br>"); document.title = "New title here!"; // Notice: this will defeat purpose of SEO. Not useful for SEO-friendly sites. document.write("title - " + document.title + "<br>"); body { font-family: Consolas, 'Courier New', monospace; } <!DOCTYPE html> <html> <head><title>Old title</title></head> <body><p> Lorem ipsum dolor sit amet, at movet detraxit mediocritatem eam, nam iusto abhorreant ne. Ei pro debet adolescens voluptaria, eu minim scaevola conceptam vel. Vim ea torquatos constituto complectitur, usu eu civibus insolens eleifend. Ex ubique quaerendum his. </p></body> </html>
对于那些寻找它的NPM版本的人,有一个完整的库:
npm install --save react-document-meta
import React from 'react';
import DocumentMeta from 'react-document-meta';
class Example extends React.Component {
render() {
const meta = {
title: 'Some Meta Title',
description: 'I am a description, and I can create multiple tags',
canonical: 'http://example.com/path/to/page',
meta: {
charset: 'utf-8',
name: {
keywords: 'react,meta,document,html,tags'
}
}
};
return (
<div>
<DocumentMeta {...meta} />
<h1>Hello World!</h1>
</div>
);
}
}
React.render(<Example />, document.getElementById('root'));
你可以使用JavaScript。一些机器人,包括谷歌,将执行JavaScript以获得SEO的好处(在SERP中显示正确的标题)。
document.title = "Google will run this JS and show the title in the search results!";
但是,这更复杂,因为您在不刷新页面或更改URL的情况下显示和隐藏选项卡。也许添加一个锚会像其他人所说的那样有所帮助。我可能需要收回我的回答。
有积极效果的文章: http://www.aukseo.co.uk/use-javascript-to-generate-seo-friendly-title-tags-1275/ http://www.ifinity.com.au/2012/10/04/Changing_a_Page_Title_with_Javascript_to_update_a_Google_SERP_Entry
不要总是假设bot不会执行JavaScript。 http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157 谷歌和其他搜索引擎都知道,索引的最佳结果是实际终端用户将在浏览器中看到的结果,包括JavaScript。
使用document.title。
请参阅本页的基本教程。
我想从未来向你问好:)最近发生的事情:
谷歌现在运行javascript,是在你的网站1 人们现在使用React.js、Ember和Angular在页面上运行复杂的javascript任务,而且它仍然被Google1索引 你可以使用html5历史api (pushState, react-router, ember, angular),它允许你做一些事情,比如为你想打开的每个选项卡设置单独的url,谷歌将索引that1
所以为了回答你的问题,你可以安全地从javascript中更改标题和其他元标签(如果你想支持非谷歌搜索引擎,你也可以添加一些像https://prerender.io这样的东西),只是让它们作为单独的url访问(否则谷歌如何知道这些是要在搜索结果中显示的不同页面?)更改SEO相关标签(在用户通过点击更改页面后)很简单:
if (document.title != newTitle) {
document.title = newTitle;
}
$('meta[name="description"]').attr("content", newDescription);
只要确保css和javascript没有在robots.txt中被阻止,你可以在谷歌网站管理员工具中使用Fetch作为谷歌服务。
1: http://searchengineland.com/tested-googlebot-crawls-javascript-heres-learned-220157