我正在为 Blogger(blogspot)创建一个 gadjet,此小部件将放置在所有页面(帖子、存档和 cutegory 页面)上,但我只需要获取当前打开的帖子的 url(不是类别页面,不是存档页面任何其他类型的页面)。
我只在我的 gadjet 中使用 javascript 代码,所以我需要在 JS 中这样做。
换句话说,我怎么知道当前页面是否是帖子页面?
我正在为 Blogger(blogspot)创建一个 gadjet,此小部件将放置在所有页面(帖子、存档和 cutegory 页面)上,但我只需要获取当前打开的帖子的 url(不是类别页面,不是存档页面任何其他类型的页面)。
我只在我的 gadjet 中使用 javascript 代码,所以我需要在 JS 中这样做。
换句话说,我怎么知道当前页面是否是帖子页面?
location
您可以在全局变量上获取有关当前页面的一些信息:
>>> location.href
"http://stackoverflow.com/questions/8288422/how-can-i-know-if-the-current-opened-page-is-a-post-page-and-not-category-or-arc/8288481#8288481"
>>> location.pathname
"/questions/8288422/how-can-i-know-if-the-current-opened-page-is-a-post-page-and-not-category-or-arc/8288481"
一旦您发现帖子和其他资源的 URL 模式是什么,就很容易了。这个简单的函数可以解决问题:
function isPostUrl(url) {
return url.match(/^http:\/\/.*\.blogspot.com\/\d{4}\/\d{2}\/.*\.html$/) != null
}
(可能可以改进,我不是 JavaScript/regex 大师)。这只是检查 URL 是否与发布地址模式匹配,例如http://foo.blogger.com/YYYY/MM/beautified-title.html
.
一点点测试(无耻的偷偷摸摸):
isPostUrl("http://nurkiewicz.blogspot.com/2011/11/spring-pitfalls-transactional-tests.html") //true
isPostUrl("http://nurkiewicz.blogspot.com/search/label/spring") //false
isPostUrl("http://nurkiewicz.blogspot.com/2011_11_01_archive.html") //false
显然,您将它与以下内容一起使用window.location.href
:
if(isPostUrl(window.location.href)) {
//...
}