此页面提供可与 Google 翻译一起使用的书签http://translate.google.com/translate_buttons但是这些书签会在同一选项卡/窗口中打开 Google 翻译并替换原始页面。如何修改 bookrmarklet 代码(见下文)以在新窗口/标签中打开?也有人可以简要解释一下代码的真正作用。非常感谢。
javascript: var t = ((window.getSelection && window.getSelection()) || (document.getSelection && document.getSelection()) || (document.selection && document.selection.createRange && document.selection.createRange().text));
var e = (document.charset || document.characterSet);
if (t != '') {
location.href = 'http://translate.google.com/?text=' + t + '&hl=en&langpair=auto|en&tbb=1&ie=' + e;
} else {
location.href = 'http://translate.google.com/translate?u=' + encodeURIComponent(location.href) + '&hl=en&langpair=auto|en&tbb=1&ie=' + e;
};
编辑:根据@DG。我已将代码修改为以下工作解决方案:
javascript: var t = ((window.getSelection && window.getSelection()) || (document.getSelection && document.getSelection()) || (document.selection && document.selection.createRange && document.selection.createRange().text));
var e = (document.charset || document.characterSet);
if (t != '') {
window.open('http://translate.google.com/?text=' + t + '&hl=en&langpair=auto|sk&tbb=1&ie=' + e)
} else {
window.open('http://translate.google.com/translate?u=' + encodeURIComponent(location.href) + '&hl=en&langpair=auto|sk&tbb=1&ie=' + e)
};
但这会在新选项卡中打开谷歌翻译,如果你想在新窗口中打开谷歌翻译,还需要传递几个参数 window.open() :
javascript: var t = ((window.getSelection && window.getSelection()) || (document.getSelection && document.getSelection()) || (document.selection && document.selection.createRange && document.selection.createRange().text));
var e = (document.charset || document.characterSet);
if (t != '') {
var url1 = 'http://translate.google.com/?text=' + t + '&hl=en&langpair=auto|sk&tbb=1&ie=' + e;
window.open(url1, '_blank', "GoogleTranslate", "height=200,width=200")
} else {
var url2 = 'http://translate.google.com/translate?u=' + encodeURIComponent(location.href) + '&hl=en&langpair=auto|sk&tbb=1&ie=' + e;
window.open(url2, '_blank', "GoogleTranslate", "height=200,width=200")
};
只有一个问题,我已经意识到在 Google Chrome 中它按预期工作。但是在 FF 18.0.2 中,它也将原始页面替换为空白,其中显示:“[object Window]”并且 URL 栏包含整个脚本,如何避免这种情况,并保持原始页面显示,而无需返回一页?
EDIT2:好的,我知道了,因为这里有人建议:什么是[对象窗口]?我添加了 void(0); 在scipt结束时。
javascript: var t = ((window.getSelection && window.getSelection()) || (document.getSelection && document.getSelection()) || (document.selection && document.selection.createRange && document.selection.createRange().text));
var e = (document.charset || document.characterSet);
if (t != '') {
var url1 = 'http://translate.google.com/?text=' + t + '&hl=en&langpair=auto|sk&tbb=1&ie=' + e;
window.open(url1, '_blank', "GoogleTranslate", "height=200,width=200")
} else {
var url2 = 'http://translate.google.com/translate?u=' + encodeURIComponent(location.href) + '&hl=en&langpair=auto|sk&tbb=1&ie=' + e;
window.open(url2, '_blank', "GoogleTranslate", "height=200,width=200")
};
void(0);
干杯