如何让谷歌翻译书签脚本在同页面的iframe中运行?
Modifying the Google Translate Bookmarklet to Use an Inline Iframe
Absolutely! You can tweak this bookmarklet to load Google Translate directly in an iframe on your current page instead of spawning a new window. Here's the breakdown of the changes and the fully updated code:
Key Changes Made
- Replaced the
window.open()calls with code that dynamically creates an iframe element - Added inline styling to position the iframe fixed in a corner (you can adjust this easily)
- Included logic to check if a translate iframe already exists—if it does, we just update its source instead of creating a duplicate
- Set appropriate attributes for the iframe (like
frameborder,allowtransparencyfor better integration)
Updated Bookmarklet Code
javascript: (function() { 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; var url; if (t !== '') { url = 'http://translate.google.com/?text=' + encodeURIComponent(t) + '&hl=en&langpair=auto|sk&tbb=1&ie=' + e; } else { url = 'http://translate.google.com/translate?u=' + encodeURIComponent(location.href) + '&hl=en&langpair=auto|sk&tbb=1&ie=' + e; } // Check if we already have a translate iframe var existingIframe = document.getElementById('google-translate-iframe'); if (existingIframe) { existingIframe.src = url; return; } // Create new iframe var iframe = document.createElement('iframe'); iframe.id = 'google-translate-iframe'; iframe.src = url; iframe.style.position = 'fixed'; iframe.style.bottom = '20px'; iframe.style.right = '20px'; iframe.style.width = '400px'; iframe.style.height = '300px'; iframe.style.border = '2px solid #ccc'; iframe.style.borderRadius = '8px'; iframe.style.zIndex = '9999'; iframe.style.backgroundColor = 'white'; // Add a close button for convenience var closeBtn = document.createElement('button'); closeBtn.textContent = 'X'; closeBtn.style.position = 'absolute'; closeBtn.style.top = '5px'; closeBtn.style.right = '5px'; closeBtn.style.padding = '2px 8px'; closeBtn.style.border = 'none'; closeBtn.style.backgroundColor = '#f44336'; closeBtn.style.color = 'white'; closeBtn.style.borderRadius = '50%'; closeBtn.style.cursor = 'pointer'; closeBtn.onclick = function() { document.body.removeChild(iframe); }; iframe.appendChild(closeBtn); document.body.appendChild(iframe); })();
Quick Customization Tips
- Adjust size/position: Modify the
width,height,bottom, andrightvalues in the iframe's style to fit your preference - Change the target language: Swap out the
skinlangpair=auto|skwith your desired language code (e.g.,enfor English,frfor French) - Tweak styling: Update the border color, border radius, or background color to match your browser's theme
内容的提问来源于stack exchange,提问作者David Devine
相关产品推荐
相关产品推荐

