电子插件在加载时将HTML内容插入到webview中

时间:2016-10-20 04:24:18

标签: webview electron

我想在加载时将几个html标签插入电子webview。 我在preload.js中尝试了下面的代码但是没有任何效果。

preload.js

window.onload = function() {
    var script = document.createElement("script");
    script.src = "https://code.jquery.com/jquery-2.1.4.min.js";
    script.onload = script.onreadystatechange = function() {
      $(document).ready(function() {

      document.getElementsByTagName("head")[0].innerHTML += "<div id="google_translate_element"></div><script type="text/javascript">function googleTranslateElementInit() {new google.translate.TranslateElement({pageLanguage: 'de', includedLanguages: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');}</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>";

};

的index.html

<!DOCTYPE html>
<html>
  <head>
    <title>jQuery injection into webview preload</title>
  </head>
  <body style="overflow:hidden;">
    <webview id="webview" preload="./preload.js" src="https://www.amazon.de/Fortan-Business-Edelstahlarmband-Machinery-Quartz/dp/B01FZEDQZG/ref=sr_1_1?ie=UTF8&qid=1476905705&sr=8-1&keywords=watches" style="position:absolute;width:100%;height:100%;"></webview>

  </body>
</html>

预期成果: 页面必须在顶部加载翻译标记

目前的结果: 没有出现翻译标签

1 个答案:

答案 0 :(得分:3)

window.onload = function() {

var script = document.createElement("script");
script.src = "https://code.jquery.com/jquery-2.1.4.min.js";
script.onload = script.onreadystatechange = function() {
  $(document).ready(function() {            
        var temp = $('<div id="google_translate_element">Translate</div><script type="text/javascript">function googleTranslateElementInit() {new google.translate.TranslateElement({pageLanguage: \'de\', includedLanguages: \'en\', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, \'google_translate_element\');}</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>');         
        $( "<div id='translateCode'></div>" ).prependTo( 'body' );
        $("#translateCode").append(temp);
  });
};
document.body.appendChild(script);
};

有效。测试