Javascript 在userscript中使用googletranslateapi
我正在为facebook制作一个用户脚本,它将使用Google translate Api帮助翻译文本。脚本正在成功地将html和css内容注入facebook 问题在于谷歌翻译Api。我正在注入一个脚本标签Javascript 在userscript中使用googletranslateapi,javascript,greasemonkey,userscripts,Javascript,Greasemonkey,Userscripts,我正在为facebook制作一个用户脚本,它将使用Google translate Api帮助翻译文本。脚本正在成功地将html和css内容注入facebook 问题在于谷歌翻译Api。我正在注入一个脚本标签 var s = document.createElement('script'); s.type="text/javascript"; s.src='https://www.google.com/jsapi?key=AIzaSyD24A-czAdTj8pPc5ugo0bYiPRx8Rc2p
var s = document.createElement('script');
s.type="text/javascript";
s.src='https://www.google.com/jsapi?key=AIzaSyD24A-czAdTj8pPc5ugo0bYiPRx8Rc2pXo';
document.body.appendChild(s);
首先,此脚本将加载url 2或3次
为了实际使用语言Api,我正在注入另一个脚本标记
var ldfun = document.createElement('script');
ldfun.setAttribute('type', 'application/javascript');
ldfun.textContent= "google.load('language','1');";
document.body.appendChild(ldfun);
此脚本未运行,有时会运行,然后页面导航消失
请帮助确保脚本未在iFrames中运行,然后使用延迟来确保加载库JS(否则,浏览器将异步运行这2个脚本) 大概是这样的:
if (window.top != window.self) //-- Don't run on frames or iframes
return;
function addJS_Node (text, s_URL)
{
var scriptNode = document.createElement ('script');
scriptNode.type = "text/javascript";
if (text) scriptNode.textContent = text;
if (s_URL) scriptNode.src = s_URL;
//--- document.head is best. Use document.body only on poor target pages.
document.head.appendChild (scriptNode);
}
//--- Load Google-Translate, JS API.
addJS_Node (null, 'https://www.google.com/jsapi?key=AIzaSyD24A-czAdTj8pPc5ugo0bYiPRx8Rc2pXo');
//--- Initialize Google-Translate after a delay to make sure it has loaded.
setTimeout (function() {
addJS_Node ("google.load('language','1');", null);
},
1500
);
确保脚本未在iFrames中运行,然后使用延迟来确保加载库JS(否则,浏览器将异步运行这2个
脚本
s)
大概是这样的:
if (window.top != window.self) //-- Don't run on frames or iframes
return;
function addJS_Node (text, s_URL)
{
var scriptNode = document.createElement ('script');
scriptNode.type = "text/javascript";
if (text) scriptNode.textContent = text;
if (s_URL) scriptNode.src = s_URL;
//--- document.head is best. Use document.body only on poor target pages.
document.head.appendChild (scriptNode);
}
//--- Load Google-Translate, JS API.
addJS_Node (null, 'https://www.google.com/jsapi?key=AIzaSyD24A-czAdTj8pPc5ugo0bYiPRx8Rc2pXo');
//--- Initialize Google-Translate after a delay to make sure it has loaded.
setTimeout (function() {
addJS_Node ("google.load('language','1');", null);
},
1500
);
我想你说的是Greasemonkey用户脚本?我想你说的是Greasemonkey用户脚本?虽然有效,但现在当google.load执行时,页面实际上会导航到该页面。如何阻止它导航?我不知道,我还无法复制这个问题。使用Ajax调用翻译工具可能会更幸运。每次加载这个笨重的库也会减少开销和延迟,但现在当google.load执行时,页面实际上会导航到该页面。如何阻止它导航?我不知道,我还无法复制这个问题。使用Ajax调用翻译工具可能会更幸运。每次加载那个笨重的库时,开销和延迟都会减少。