Skip to content

Instantly share code, notes, and snippets.

@blacklight
Last active July 7, 2020 18:18
Show Gist options
  • Save blacklight/fad389393d4dea47cece25c34b8dbb8c to your computer and use it in GitHub Desktop.
Save blacklight/fad389393d4dea47cece25c34b8dbb8c to your computer and use it in GitHub Desktop.
// Platypush user script to translate a web page through the Google Translate API
async (app, args) => {
const dom = await app.getDOM();
// Translate the page through the Platypush Google Translate plugin
// (https://platypush.readthedocs.io/en/latest/platypush/plugins/google.translate.html).
// The plugin also splits the HTML in multiple requests if too long
// to circumvent Google's limit on maximum input text.
const response = await app.run({
action: 'google.translate.translate',
args: {
text: dom.body.innerHTML,
format: 'html',
target_language: 'en',
}
}, args.host);
// The new body will contain a <div> with the translated HTML,
// a hidden <div> with the original HTML and a top fixed button
// to switch back to the original page.
const translatedDiv = `
<div class="platypush__translated-container">
<div class="platypush__translated-banner">
<button type="button"
onclick="document.body.innerHTML = document.querySelector('.platypush__original-body').innerHTML">
See Original
</button>
</div>
<div class="platypush__translated-body">
${response.translated_text}
</div>
<div class="platypush__original-body">
${dom.body.innerHTML}
</div>
</div>`;
const style = `
<style>
.platypush__original-body {
display: none;
}
.platypush__translated-banner {
position: fixed;
background: white;
color: black;
z-index: 99999;
}
</style>`;
// Reconstruct the DOM and change it.
dom.head.innerHTML += style;
dom.body.innerHTML = translatedDiv;
await app.setDOM(`<html>${dom.getElementsByTagName('html')[0].innerHTML}</html>`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment