【问题标题】:Best way to differentiate between different pages inside greasemonkey script?区分greasemonkey脚本中不同页面的最佳方法?
【发布时间】:2017-01-05 11:05:42
【问题描述】:
例如,我想向 google.com 主页和 google.com 搜索结果页面添加一些功能,并且我想在一个greasemonkey 脚本中完成,我这样做了:
@include http://google.com*
然后我检查,如果是主页,我会在搜索框下添加第三个按钮,例如,如果是结果页面,我会更改字体或类似的东西。
区分这些页面的最佳方法是什么?我目前有
if (document.URL==="homepage") {
add button
} else if (document.URL==="searchpage") {
change font
}
切换会更好吗?有没有更好的解决方案?
【问题讨论】:
标签:
javascript
firefox
greasemonkey
userscripts
【解决方案1】:
switch 比系列if/else if 更快更高效
我经常为此目的使用。
// caching path is faster (although the difference is only milliseconds)
var path = location.pathname;
switch (true) {
/* ----- Home page ----- */
case path.indexOf('/path1') !== -1:
addButton();
break;
/* ----- Search page ----- */
case path.indexOf('/path2') !== -1:
changeFont();
break;
}
更新:
使用 ES6 includes()
var path = location.pathname;
switch (true) {
/* ----- Home page ----- */
case path.includes('/path1'):
addButton();
break;
/* ----- Search page ----- */
case path.includes('/path2'):
changeFont();
break;
}