1
javascript: function translate(word){ var glf = document.getElementById("glf"); glf.contentWindow.gtrans(word); }; function findAndReplace(searchText, replacement, searchNode) { var regex = typeof searchText === 'string' ? new RegExp(searchText, 'g') : searchText, childNodes = (searchNode || document.body).childNodes, cnLength = childNodes.length, excludes = 'html,head,style,title,link,meta,script,object,textarea,iframe'; while (cnLength--) { var currentNode = childNodes[cnLength]; if (currentNode.nodeType === 1 && (excludes + ',').indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) { arguments.callee(searchText, replacement, currentNode); } if (currentNode.nodeType !== 3 || !regex.test(currentNode.data) ) { continue; } var parent = currentNode.parentNode, frag = (function(){ var html = currentNode.data.replace(regex, replacement), wrap = document.createElement('div'), frag = document.createDocumentFragment(); wrap.innerHTML = html; while (wrap.firstChild) { frag.appendChild(wrap.firstChild); } return frag; })(); parent.insertBefore(frag, currentNode); parent.removeChild(currentNode); } }; function inject(){ findAndReplace('\\b[^ ]+\\b', function(term){ return '<span onmouseover="translate(this)">' + term + '</span>'; }); }; function init() { var glf = document.createElement('iframe'); glf.id = 'glf'; glf.width=114; glf.height=38; glf.frameborder=0; glf.style.borderWidth='thin'; glf.style.borderStyle='outset'; glf.style.position='fixed'; glf.style.top='10px'; glf.style.right='10px'; document.body.appendChild(glf); var doc = glf.contentDocument; doc.open(); doc.write('<head><title>Sample html</title><script type="text/javascript" src="http://www.google.com/jsapi"></script><script type="text/javascript">google.load("language", "1");function gtrans(word) {if(word.title) return; word.title = "translating..."; var text = word.innerHTML; google.language.detect(text, function(result) { if (!result.error && result.language) { google.language.translate(text, result.language, "zh-tw", function(result) {if (result.translation) { word.title = text + ": " + result.translation;}});}});};</script></head><body style="margin:2; background-color: white;"><div id="branding" style="width : 112px; height : 20px; text-align: left;">Chrome%E5%B0%8F%E5%AD%97%E5%85%B8</div><script>google.language.getBranding("branding");</script></body>'); doc.close(); document.body.appendChild(glf); inject(); }; init();