区分 greasemonkey 脚本中不同页面的最佳方法?
Best way to differentiate between different pages inside greasemonkey script?
例如,我想向 google.com 主页和 google.com 搜索结果页面添加一些功能,我想在一个 greasemonkey 脚本中完成,我这样做:
@include http://google.com*
然后我检查一下,如果是主页,我会在搜索框下面添加第三个按钮,例如,如果是结果页面,我会更改字体或类似的东西。
区分这些页面的最佳方式是什么?我目前
if (document.URL==="homepage") {
add button
} else if (document.URL==="searchpage") {
change font
}
switch会更好吗?有更好的解决方案吗?
switch
比系列 if/else if
更快更高效
我经常使用 is 来达到这个目的。
// 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;
}
例如,我想向 google.com 主页和 google.com 搜索结果页面添加一些功能,我想在一个 greasemonkey 脚本中完成,我这样做:
@include http://google.com*
然后我检查一下,如果是主页,我会在搜索框下面添加第三个按钮,例如,如果是结果页面,我会更改字体或类似的东西。
区分这些页面的最佳方式是什么?我目前
if (document.URL==="homepage") {
add button
} else if (document.URL==="searchpage") {
change font
}
switch会更好吗?有更好的解决方案吗?
switch
比系列 if/else if
我经常使用 is 来达到这个目的。
// 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;
}