Electron-Insert HTML content into webview while loading - webview

I want to insert few html tags into electron webview while loading.
I tried below code in preload.js but that doesn't have any effect.
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>
Expected Result :
Page has to loaded with translate tag on top
Current result :
No translate tag is appearing

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);
};
It works. Tested.

Related

Can´t reproduce bootstrap documentation using js example. Why?

I´m trying to reproduce bootstrap documentation example:
https://getbootstrap.com/docs/5.2/components/list-group/#javascript-behavior
With 2 diferences: using js to create the html tags and using a nested list instead of single list.
The 'activate' highlight doesn´t work and the right side content doesn´t change. Need help on why and how to make it work.
I´m also trying to create a collapse effect for the nested list when the parent item is clicked.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<!-- <link rel="stylesheet" href="style.css"> -->
</head>
<body>
<div id="tree"></div>
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<script>
function clearChildren(node){
while(node.children.length > 0)
node.removeChild(node.lastElementChild)
}
let idCounter = 0
function createNode(name,meta={}){
return {
name,
id: idCounter++,
children:new Array(),
meta
}
}
function makeTreeTable(parentElement, rootNode){
clearChildren(parentElement)
parentElement.setAttribute('class', 'row')
//Make Tree Div
const divTree = document.createElement('div')
divTree.setAttribute('class','col-8')
divTree.setAttribute('id', 'div-tree')
parentElement.appendChild(divTree)
//Make Meta Div
const divMeta = document.createElement('div')
divMeta.setAttribute('class','col-4')
divMeta.setAttribute('id', 'div-node')
parentElement.appendChild(divMeta)
const metaDisplay = document.createElement('div')
metaDisplay.setAttribute('class','tab-content')
metaDisplay.setAttribute('id','nav-tabContent')
divMeta.appendChild(metaDisplay)
maketree(divTree, rootNode, metaDisplay)
}
let activeMeta = 'tab-pane fade show active'
function createMetaList(treeNode){
const metaList = document.createElement('div')
console.log(treeNode.id)
metaList.setAttribute('id', `${treeNode.id}-meta`)
metaList.setAttribute('class',activeMeta)
activeMeta = 'tab-pane fade'
metaList.setAttribute('role','tabpanel')
metaList.setAttribute('aria-labelledby',treeNode.id)
for (const [key, value] of Object.entries(treeNode.meta)) {
const metaItem = document.createElement('div')
metaItem.innerHTML = `${key} : ${value}`
metaList.appendChild(metaItem)
}
return metaList
}
let activeNode = 'list-group-item list-group-item-action active'
function maketree(parentElement, nodeTgt, metaDisplay) {
//Make ul node
const ul = document.createElement("div");
ul.setAttribute('class', 'list-group')
ul.setAttribute('id','nodeTgt.name')
ul.setAttribute('role','tablist')
//Make all li´s nodes
for(const node of nodeTgt.children){
const li = document.createElement("a");
li.innerHTML = node.name;
li.setAttribute("id", node.id);
li.setAttribute("class", activeNode)
activeNode = 'list-group-item list-group-item-action'
li.setAttribute('data-bs-toogle','list')
li.setAttribute('role','tab')
li.setAttribute('href',`#${node.id}-meta`)
li.setAttribute('aria-controls',`${node.id}-meta`)
li.addEventListener('click',(e)=>{
e.stopPropagation()
console.log('clicked ', node.name)
})
ul.appendChild(li);
metaDisplay.appendChild(createMetaList(node))
//Make recursive items
if(nodeTgt.children.length > 0)
maketree(li,node, metaDisplay)
}
parentElement.appendChild(ul)
}
function makeMeta(i){
return{
meta1:`this is ${i}`,
meta2:`this is ${++i}`,
meta3:`this is ${++i}`,
}
}
const root = createNode('root', makeMeta(0))
root.children.push(createNode('node1', makeMeta(1)))
root.children.push(createNode('node2', makeMeta(2)))
root.children.push(createNode('node3', makeMeta(3)))
const node1 = root.children[0]
const node2 = root.children[1]
const node3 = root.children[2]
node1.children.push(createNode('node11', makeMeta(11)))
node1.children.push(createNode('node12', makeMeta(12)))
node2.children.push(createNode('node21', makeMeta(21)))
node2.children.push(createNode('node22', makeMeta(22)))
node3.children.push(createNode('node31', makeMeta(31)))
node3.children.push(createNode('node32', makeMeta(32)))
const node11 = node1.children[0]
const node12 = node1.children[1]
const node31 = node3.children[0]
const node32 = node3.children[1]
node11.children.push(createNode('node111', makeMeta(111)))
node11.children.push(createNode('node112', makeMeta(112)))
node12.children.push(createNode('node121', makeMeta(121)))
node12.children.push(createNode('node122', makeMeta(122)))
node31.children.push(createNode('node311', makeMeta(111)))
node31.children.push(createNode('node312', makeMeta(112)))
node32.children.push(createNode('node321', makeMeta(121)))
node32.children.push(createNode('node322', makeMeta(122)))
makeTreeTable(document.querySelector('#tree'), root)
</script>
</body>
</html>
Thanks
You need to initialize the created elements individually.
https://getbootstrap.com/docs/5.2/components/list-group/#via-javascript
Put the following at the end of your script:
const triggerTabList = document.querySelectorAll('#tree a')
triggerTabList.forEach(triggerEl => {
const tabTrigger = new bootstrap.Tab(triggerEl)
triggerEl.addEventListener('click', event => {
event.preventDefault()
tabTrigger.show()
})
})
Then you will see an error that says "#1-meta" is not a valid selector. I think you need to refactor your code to have all of the ids start with a letter [a-z]. So you want to use "meta-1" format instead.

Custom JQuery Mobile Button

I'm using jQuery Mobile 1.3, and attempted to follow a tutorial in order to create my own custom widget.
I'm getting stuck on the very first step, and I'm not sure if I'm following the right example for the right version of jQuery mobile.
There is no error on the page, my element is just never enriched.
(function($) {
$.widget("mobile.target", $.mobile.button, {
/** Available options for the widget are specified here, along with default values. */
options: {
inline: false,
mode: "default",
height: 200
},
/** Mandatory method - automatically called by jQuery Mobile to initialise the widget. */
_create: function() {
var inputElement = this.element;
var opts = $.extend(this.options, inputElement.data("options"));
$(document).trigger("targetcreate");
inputElement.after("<button>" + inputElement.val() + "</button>");
},
/** Custom method to handle updates. */
_update: function() {
var inputElement = this.element;
var opts = $.extend(this.options, inputElement.data("options"));
$(document).trigger("targetupdate");
inputElement.siblings("button").text(inputElement.val());
},
/* Externally callable method to force a refresh of the widget. */
refresh: function() {
return this._update();
}
});
/* Handler which initialises all widget instances during page creation. */
$(document).bind("pagecreate", function(e) {
$(document).trigger("targetbeforecreate");
return $(":jqmData(role='target')", e.target).target();
});
})(jQuery);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<input type="button" data-role="target" value="inp1">
<input type="button" value="inp2">
<div data-role="target">div1</div>
<div type="button">div2</div>
</body>
</html>
(function($) {
$.widget("mobile.target", $.mobile.button, {
/** Available options for the widget are specified here, along with default values. */
options: {
inline: false,
mode: "default",
height: 200
},
/** Mandatory method - automatically called by jQuery Mobile to initialise the widget. */
_create: function() {
var inputElement = this.element;
var opts = $.extend(this.options, inputElement.data("options"));
$(document).trigger("targetcreate");
inputElement.after("<button>" + inputElement.val() + "</button>");
},
/** Custom method to handle updates. */
_update: function() {
var inputElement = this.element;
var opts = $.extend(this.options, inputElement.data("options"));
$(document).trigger("targetupdate");
inputElement.siblings("button").text(inputElement.val());
},
/* Externally callable method to force a refresh of the widget. */
refresh: function() {
return this._update();
}
});
/* Handler which initialises all widget instances during page creation. */
$(document).bind("pagecreate", function(e) {
$(document).trigger("targetbeforecreate");
return $(":jqmData(role='target')", e.target).target();
});
})(jQuery);
Expected output was a custom JQueryMobile button that inherits from the JQueryMobile button. Not just a tiny html5 button in a div. e.g. Div1 rendering the same as Div2 but with customized changes made.
You are trying to get an input element in jQuery code. But you defined a div element in the HTML page.
That is the problem. Change it to input.
Check the below code
The tutorial you followed states that only use the :jqmData if you didn't use the HTML5 data attribute. Remove it
(function($) {
$.widget("mobile.target", $.mobile.widget, {
options: {
inline: false,
mode: "default",
height: 200
},
_create: function() {
var inputElement = this.element;
var opts = $.extend(this.options, inputElement.data("options"));
$(document).trigger("targetcreate");
inputElement.after("<button>"+inputElement.val()+"</button>");
},
_update: function() {
var inputElement = this.element;
var opts = $.extend(this.options, inputElement.data("options"));
$(document).trigger("targetupdate");
inputElement.siblings("button").text(inputElement.val());
},
refresh: function() {
return this._update();
}
});
$(document).bind("pagecreate", function(e) {
$(document).trigger("mywidgetbeforecreate");
return $("[role='target']", e.target).target();
});
})(jQuery);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<input type="button" data-role="target" value="inp1">
<input type="button" value="inp2">
<div type="button" data-role="target">div1</div>
<div type="button">div2</div>
</body>
</html>

Canvas not defined

I am experimenting with Raymond Camden's watermark code and also example from Phonegap camera API.
Camera works well.
However,
Uncaught ReferenceError: canvas is not defined
is shown in LogCat.
I have tried to place the variables in function as well as global. But the error still appears. My code is as below:
<!DOCTYPE html>
<head>
<script type="text/javascript" charset="utf-8" src="cordova-2.7.0.js"></script>
<link rel="stylesheet" type="text/css" href="jquery/css/jquery.mobile-1.3.1.min.css"/>
<script type="text/javascript" charset="utf-8" src="jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript" charset="utf-8" src="jquery/jquery.mobile-1.3.1.min.js"><script>
<script type="text/javascript" charset="utf-8">
var watermark;
var canvasDOM;
var canvas;
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
} </script>
<script type="text/javascript" charset="utf-8">
canvasDOM = $("myCanvas")[0];
canvas = canvasDOM.getContext("2d");
watermark = new Image();
watermark.src = "q1.jpg";
function cybershot() {
navigator.camera.getPicture(camSuccess, camError, {quality: 75, targetWidth: 400, targetHeight: 400, destinationType: Camera.DestinationType.FILE_URI});
}
function camError(e) {
console.log("Camera Error");
console.log(JSON.stringify(e));
}
function camSuccess(picuri) {
console.log("Camera Success");
var img = new Image();
img.src=picuri;
img.onload = function(e) {
canvas.drawImage(img, 0, 0);
canvas.drawImage(watermark, canvasDOM.width-watermark.width, canvasDOM.height - watermark.height);
}
}
</script>
<style>
#myCanvas {
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<h1>Watermark Camera</h1>
<button onclick="cybershot();">Capture Photo</button> <br>
<p/>
<canvas id="myCanvas"></canvas>
</body>
</html>
Solution
There's an error in this code.
Javascript used must be placed inside a onDeviceReady() function. It is an equivalent of classic jQuery document ready.
In this case javascript is executed inside a HEAD before BODY content is loaded into the DOM. onDeviceReady() will delay its execution until everything is loaded into the DOM.
Fixed code
Your javascript should look like this:
var canvas;
var watermark;
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
canvasDOM = $("myCanvas")[0];
canvas = canvasDOM.getContext("2d");
watermark = new Image();
watermark.src = "q1.jpg";
}
function cybershot() {
navigator.camera.getPicture(camSuccess, camError, {quality: 75, targetWidth: 400, targetHeight: 400, destinationType: Camera.DestinationType.FILE_URI});
}
function camError(e) {
console.log("Camera Error");
console.log(JSON.stringify(e));
}
function camSuccess(picuri) {
console.log("Camera Success");
var img = new Image();
img.src=picuri;
img.onload = function(e) {
canvas.drawImage(img, 0, 0);
canvas.drawImage(watermark, canvasDOM.width-watermark.width, canvasDOM.height - watermark.height);
}
}
Try moving this part (the entire content of the script block) canvasDOM = $("myCanvas")[0]; into $(document).ready(function(){ });

How to scroll the checkboxes inside a dropdown by jquery.mobile.scrollview.js?

I have implemented the Jquery.mobile.scrollview.js and i am able to scroll the dropdown,But what happens is when i click to scroll the checkboxes inside the dropdown the checkboxes gets invisible and only the text is shown.. IS there is any workaround is there... Please let me know..
IS there any example on this..... I am adding my code below .. and giving data-scroll = 'y' in my div part ...
<!-- Scroll View code -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#evtCatcher
{
}
#evtCatcher .ui-scrollview-view
{
padding: 10px;
}
</style>
<script src="jsScroll/jquery.js" type="text/javascript"></script>
<script src="jsScroll/jsdefault.js" type="text/javascript"></script>
<script src="jsScroll/jquery.easing.1.3.js" type="text/javascript"></script>
<script src="jsScroll/jquery.mobile.scrollview.js" type="text/javascript"></script>
<script src="jsScroll/iscroll.js" type="text/javascript""></script>
<script type="text/javascript">
function fnClick() {
alert('clicked');
}
</script>
<script>
$("[ data-role=page]").live("pageshow", function(event) {
var $page = $(this);
$page.find("[data-scroll]:not(.ui-scrollview-clip)").each(function() {
var $this = $(this);
// XXX: Remove this check for ui-scrolllistview once we've
// integrated list divider support into the main scrollview class.
if ($this.hasClass("ui-scrolllistview"))
$this.scrolllistview();
else {
var st = $this.data("scroll") + "";
var paging = st && st.search(/^[xy]p$/) != -1;
var dir = st && st.search(/^[xy]/) != -1 ? st.charAt(0) : null;
var opts = {};
if (dir)
opts.direction = dir;
if (paging)
opts.pagingEnabled = true;
$this.scrollview(opts);
}
});
changeDelayFormElementClick();
});
function changeScrollMethod() {
var val = $("#s_method").val();
var $sv = $("#evtCatcher").scrollview("scrollTo", 0, 0);
if (val === "scroll") {
$sv.css("overflow", "scroll");
}
else {
$sv.css("overflow", "hidden");
}
$sv.data("scrollview").options.scrollMethod = val;
}
function changeDelayFormElementClick() {
$("#evtCatcher").data("scrollview").options.delayedClickEnabled = ($("#s_delay").val() === "yes");
}
var cb_hd_pd,
cb_hd_sp,
cb_hm_pd,
cb_hm_sp,
cb_hu_pd,
cb_hu_sp;
var hd = $.mobile.scrollview.prototype._handleDragStart;
var hm = $.mobile.scrollview.prototype._handleDragMove;
var hu = $.mobile.scrollview.prototype._handleDragStop;
function getDummyEvent(o) {
return { target: o.target, _pd: false, _sp: false, preventDefault: function() { this._pd = true; }, stopPropagation: function() { this._sp = true; } };
}
function updateEvent(e, cb_pd, cb_sp) {
if (cb_pd.checked)
e.preventDefault();
if (cb_sp.checked)
e.stopPropagation();
}
$.mobile.scrollview.prototype._handleDragStart = function(e, x, y) {
hd.call(this, getDummyEvent(e), x, y);
updateEvent(e, cb_hd_pd, cb_hd_sp);
};
$.mobile.scrollview.prototype._handleDragMove = function(e, x, y) {
hm.call(this, getDummyEvent(e), x, y);
updateEvent(e, cb_hm_pd, cb_hm_sp);
};
$.mobile.scrollview.prototype._handleDragStop = function(e) {
hu.call(this, getDummyEvent(e));
updateEvent(e, cb_hu_pd, cb_hu_sp);
};
$(function() {
cb_hd_pd = $("#cb_hd_pd")[0];
cb_hd_sp = $("#cb_hd_sp")[0];
cb_hm_pd = $("#cb_hm_pd")[0];
cb_hm_sp = $("#cb_hm_sp")[0];
cb_hu_pd = $("#cb_hu_pd")[0];
cb_hu_sp = $("#cb_hu_sp")[0];
});
</script>
Thanks in Advance :)

Why can't I get the icons when I use jQueryUI with Google Ajax API within Jetpack?

I can't get any icons to be shown on a modal dialog box when I try to use jQueryUI via Google Ajax API. The icons do not appear but when I click on the locations where they are supposed to be the relevant functinality works (e.g. I can resize and close the modal dialog box). Here's the problematic screenshot and my code for Jetpack:
http://www.flickr.com/photos/64416865#N00/4303522684/
function testJQ() {
var doc = jetpack.tabs.focused.contentDocument;
var win = jetpack.tabs.focused.contentWindow;
$.get("http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js", function(js) {
var script = doc.createElement("script");
script.innerHTML = js;
doc.getElementsByTagName('HEAD')[0].appendChild(script);
$.get("http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js", function(js) {
var script = doc.createElement("script");
script.innerHTML = js;
doc.getElementsByTagName('HEAD')[0].appendChild(script);
$.get("http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/ui-lightness/jquery-ui.css", function(js) {
var style = doc.createElement("style");
style.innerHTML = js;
doc.getElementsByTagName('HEAD')[0].appendChild(style);
script = doc.createElement("script");
script.innerHTML = 'var myDialogFunc = function () {';
script.innerHTML += '$("<div id=dialog title=\\"Basic Dialog\\"> <p>The dialog window can be moved, resized and closed with the X icon.</p></div>").appendTo("body");';
script.innerHTML += '$("#dialog").dialog({'
script.innerHTML += ' bgiframe: true, height: 140, modal: true';
script.innerHTML += ' });';
script.innerHTML += '};';
doc.body.appendChild(script);
win.wrappedJSObject['myDialogFunc']();
});
});
});
}
On the other hand, in a simple html document I can use Google Ajax API, load jquery and jQueryUI and get the icons correct without any problems. Here's the screenshot and source code that works as I expect:
http://www.flickr.com/photos/64416865#N00/4303522672/
<html>
<head>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
var myDialogFunc = function () {
$("#dialog").dialog({
bgiframe: true,
height: 140,
modal: true
});
};
// Load jQuery
google.load("jquery", "1.4.0");
google.load("jqueryui", "1.7.2");
google.setOnLoadCallback(function() {
myDialogFunc();
});
</script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/ui-lightness/jquery-ui.css" type="text/css" media="all" />
</head>
<body>
<div id="dialog" title="Basic Dialog">
<p>The dialog window can be moved, resized and closed with the X icon.</p>
</div>
</body>
Any ideas about why I can't get the icons in my Jetpack version?
Code below solves my problem:
js = js.replace("url(", "url(http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/ui-lightness/", "g");
style.innerHTML = js;

Resources