Javascript实现网页无刷新翻译&做成Bookmarklet(书签工具)

最近要做网站的在线翻译功能,但网上的代码都不太好用,都是整个页面一起刷新的。所以我就自己通过翻译网站的API写了这个翻译功能,并且可以做成Bookmarklet(书签工具),就算不用在网站也能用于访问其他的网页。这次因为要考虑到书签工具的问题,所以没有使用到Javascript的扩展库,但如果你觉得翻译网站自带的样式太难看,你也可以用Javascript来重写它。

我调用了2个翻译网站的翻译接口,它们分别是必应和谷歌。其实我只在项目中使用了必应翻译的功能,但后来做有SSL(就是以Https方式访问)的登录页面和Bookmarklet时就发现必应翻译并不能翻译有SSL的网站。一直以来我都有用谷歌翻译来手动翻译网页的,也清楚它能翻译有SSL的网站,然后我又在项目中实现了谷歌翻译的功能。就这样,我实现了2个翻译的功能。

范例代码:

<html lang="zh-CN">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>页面翻译范例</title>
</head>

<body>
<script>
function BingTranslate(){   //必应翻译
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://labs.microsofttranslator.com/bookmarklet/default.aspx?f=js&to=zh-chs';
    document.body.insertBefore(script, document.body.firstChild);
}

function GoogleTranslate(){ //谷歌翻译,本地运行有可能无反应
    document.cookie = "googtrans="+ escape ("/auto/zh-CN") + ";expires=0";  //设置默认翻译语言

    if(document.getElementById('google_translate_element')){   
        return false;
    }
    
    var link = document.createElement('script');
    link.type = 'text/javascript';
    link.src = 'https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';
    document.body.insertBefore(link, document.body.firstChild);
    
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.text = 'function googleTranslateElementInit(){new google.translate.TranslateElement({pageLanguage:"",layout:google.translate.TranslateElement.InlineLayout.SIMPLE},"google_translate_element")};';
    document.body.insertBefore(script, document.body.firstChild);
  
    var div = document.createElement('div');
    div.id = 'google_translate_element';
    div.innerText = '';
    div.style.display = 'none'; //隐藏语言选框,某些情况下会出现这个多余的选框
    document.body.insertBefore(div, document.body.firstChild);
}

</script>
<div><a href="javascript:BingTranslate();">必应翻译</a><a href="javascript:GoogleTranslate();">谷歌翻译</a></div>

<p>This is an online translator that provides accurate translations between 75 different languages including English, Spanish, <b>Chinese</b> and more.</p>

</body>
</html>

书签工具的添加方法:

[重要说明]

以下翻译工具的Javascript代码只在Chrome下测试通过。所以我只放出Chrome的添加书签工具的图文教程,其他浏览器同理。

先打开Chrome浏览器,然后在右上角找到“三横杠”再找到“书签管理器”。

打开“书签管理器”后,在“书签栏”项右键点击“添加网页”。

然后右边书签列表最下面会出现一个新增的书签。

[必应翻译]

javascript:(function(){var script=document.createElement("script");script.type="text/javascript";script.src="http://labs.microsofttranslator.com/bookmarklet/default.aspx?f=js&to=zh-chs";document.body.insertBefore(script,document.body.firstChild)})();

[谷歌翻译]

javascript:(function(){document.cookie="googtrans="+escape("/auto/zh-CN")+";expires=0";if(document.getElementById("google_translate_element")){return false}var link=document.createElement("script");link.type="text/javascript";link.src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";document.body.insertBefore(link,document.body.firstChild);var script=document.createElement("script");script.type="text/javascript";script.text='function googleTranslateElementInit(){new google.translate.TranslateElement({pageLanguage:"",layout:google.translate.TranslateElement.InlineLayout.SIMPLE},"google_translate_element")};';document.body.insertBefore(script,document.body.firstChild);var div=document.createElement("div");div.id="google_translate_element";div.innerText="";div.style.display="none";document.body.insertBefore(div,document.body.firstChild)})();

在“名称”处填入书签工具的名称,在“网址”处填入上面提供的翻译接口的Javascript代码。

填写完后就点击下其他地方,它就会自动保存了。

经过上面的步骤就设置好了书签工具了,接着就是使用工具。先打开一个你需要翻译的网页,再从书签里面找到刚刚设置的翻译工具,然后点击即可自动翻译。

最后再低调补充一句,使用谷歌翻译有时会因为墙的问题而导致翻译失败。

标签:工具, 实现, javascript, 网页, 无刷新, 翻译, bookmarklet, 书签

该文章由 Shiqi Qiu 原创并发布在 被遗忘的曙光 技术博客

转载请标明来源:http://blog.fdawn.com/Front-End/24.html

已有 28 条评论

  1. Sharyl

    My brother suggested I might like this web site.

    He was entirely right. This put up actually made
    my day. You can not imagine just how so much time I
    had spent for this information! Thank you!

  2. cristaldenos

    Hiya very nice site!! Guy .. Excellent .. Wonderful ..
    I will bookmark your web site and take the feeds
    also? I am happy to search out so many useful info here in the submit, we'd like develop more
    techniques on this regard, thanks for sharing.
    . . . . .

  3. Glennaha

    These are in fact fantastic ideas in concerning blogging.
    You have touched some nice things here. Any way keep up wrinting.

  4. gutturalshame

    Loving the info on this site, you have done outstanding job on the articles.

  5. upsetapex

    Glad to be one of the visitors on this awing website :D.

  6. Royal

    Sweet blog! I found it while surfing around on Yahoo News.
    Do you have any tips on how to get listed in Yahoo News?

    I've been trying for a while but I never seem to get there!
    Many thanks

  7. Darren

    Hi, Neat post. There's a problem together with your web site in web explorer, might check this?
    IE nonetheless is the market chief and a huge element of folks will leave out your excellent writing because of
    this problem.

  8. clitus516

    Thanks for writing!

  9. darcy4sharp7

    You can definitely see your expertise within the paintings
    you write. The sector hopes for even more passionate writers like you who are
    not afraid to say how they believe. Always follow your heart.

  10. Quyen

    These are in fact fantastic ideas in about blogging.
    You have touched some fastidious factors here.
    Any way keep up wrinting.

  11. jimdo

    No uncertainty very soon it will be well-known, due to
    its quality contents.

  12. peacefulroad1728

    Hi i am kavin, its my first time to commenting anywhere, when i read this article i thought i could also create comment due to this brilliant article.

  13. maritzablinks

    Hey there, You've done a great job. I will certainly digg it
    and in my view recommend to my friends. I am sure they'll
    be benefited from this web site.

  14. styletigh

    No uncertainty very soon it will be renowned, due to its quality contents.

  15. alfrediabocsk

    Hi there, You have performed an incredible job. I'll certainly digg it and in my view suggest to my friends.
    I am sure they'll be benefited from this web site.

  16. jimdo

    Hey very cool website!! Guy .. Beautiful .. Superb .. I will bookmark your web site and take the feeds additionally?

    I am glad to search out so many helpful info here in the submit,
    we'd like work out more strategies in this regard, thank you for sharing.
    . . . . .

  17. gracevig

    This is the perfect website for everyone who wants to find out about this topic.
    You understand a whole lot its almost hard to argue with you
    (not that I personally will need to?HaHa). You definitely put a new spin on a subject that has been written about for
    decades. Wonderful stuff, just wonderful!

  18. taller-people

    I drop a comment whenever I especially enjoy a
    article on a website or I have something to valuable
    to contribute to the discussion. It's triggered by the fire communicated in the post
    I read. I was actually excited enough to drop a thought ;) I do have 2 questions for you if it's allright.
    Is it just me or do a few of these remarks come across
    like they are left by brain dead people? :-P And, if you are posting at
    other online social sites, I'd like to keep up with anything fresh you have to
    post. Would you make a list all of your communal sites like your twitter feed,
    Facebook page or linkedin profile?

  19. snack

    Just what I was looking for, thanks for posting.

  20. ameblo

    Loving the information on this web site, you have done great job on the
    articles.

  21. francisco

    Hi my family member! I wish to say that this post is amazing, nice written and include
    almost all significant infos.

  22. kone468

    I'm so happy to read this. This is the type of manual that needs to be
    given and not the random misinformation that's at the other blogs.
    Appreciate your sharing this greatest doc.

  23. Tiffany

    Just what I was looking for, thank you for posting.

  24. alivenot

    Loving the info on this site, you have done outstanding job on the articles.

  25. dennastock

    Inspiring quest there. What occurred after?
    Good luck!

  26. Obscene

    We're a bunch of volunteers and starting a new scheme in our community.
    Your site provided us with helpful info to work on. You have done a formidable job and our entire group shall be grateful to you.

  27. kerrimatzen

    Thanks for finally writing about this article, Loved it!

  28. Goo

    The details talked about in the post are several of the best offered.

添加新评论