Dynamically adding multiple events to multiple webviews - javascript

Im new to using Electron and also kinda new to using the webview tag, so I pre-apologize for maybe not knowing something really obvious.
Im trying to dynamiclly create web views and add the following events to them.
did-start-loading
did-stop-loading
did-finish-load
page-title-updated
dom-ready
Im using a mix of Jquery and pure javascript to do this but currently im not having much luck. I have attached my code below so you can try find anything obvious there. Im not getting any javascript errors in the debug menu but at the same time none of it seems to be working.
function AddTab(URL){
tabcount++;
var NewTab = '<li href="#content-' + tabcount + '" id="tab' + tabcount + '" class="current"><img src="System_Assets/icons/Logo.png" /><span>Tab Home</span><a class="TabClose" href="#"></a></li>';
var NewContent = '<div id="content-' + tabcount + '" class="ContentHolder" style="display:block;"><webview id="webview-content-' + tabcount + '" src="http://www.ohhaibrowser.com"></webview></div>';
ChangeCurrent("");
//Hide current tabs
$(".ContentHolder").css("display", "none");
//Show new tab
$("#tabs-menu").append(NewTab);
$("#BrowserWin").append(NewContent);
$("#CurWebWin").val("webview-content-" + tabcount);
AddListeners("webview-content-" + tabcount,"tab" + tabcount);
UpdateTabCount();
}
function UpdateTabCount(){
$("#HideShow").text(tabcount);
}
function AddListeners(webview,tabid)
{
element = document.getElementById(webview);
element.addEventListener("did-start-loading", function() {
loadstart(tabid);
});
element.addEventListener("did-stop-loading", function() {
loadstop(tabid,webview);
});
element.addEventListener("did-finish-load", function() {
loadstop(tabid,webview);
});
element.addEventListener("page-title-updated", function() {
loadstop(tabid,webview);
});
element.addEventListener("dom-ready", function() {
domloaded(tabid,webview);
});
}
function loadstart(tabid)
{
$("#" + tabid + " span").val('Loading...');
//$("#" + tabid + " img")
}
function loadstop(tabid, webview)
{
$("#" + tabid + " span").val('');
}
function domloaded(tabid, webview)
{
element = document.getElementById(webview);
$("#" + tabid + " span").val(element.getURL());
}

You have to set Preload call to make change in Webview
browser.html
<script src="browser.js"></script>
<webview src="https://www.google.com/watch?v=1osdnKzj-1k" preload="./inject.js" style="width:640px; height:480px"></webview>
create sample js file name called inject.js
inject.js
__myInjection={
onloada : function() {
var script = document.createElement("script");
script.src = "https://code.jquery.com/jquery-2.1.4.min.js";
$("#header").html('<h1>Sample work</h1>\
<p>Hello, Google</p>\
Click me');
document.body.appendChild(script);
}
}
now in browser.js
onload = function() {
var webview = document.querySelector('webview');
webview.addEventListener("dom-ready", function(){
webview.executeJavaScript('__myInjection.onloada ()')
// webview.openDevTools();
});
doLayout();

Related

deleting elements created by jquery in a sequence

I'm trying to build my first plugin using jquery.
So far successful, but I'm stuck in deleting the notifications.
I was able to delete the notification on a click event.
Notification.prototype.destroy = function(element) {
var self = this;
element.closest('.notification-container').remove();
};
And I call that function inside init method.
Notification.prototype.init = function() {
var self = this;
self.$el.on('click', function() {
self.build();
});
self.$body.on('click', '.close', function() {
self.destroy(this);
})
};
Now I wanted to give a auto close option to the user, and I thought of using the setTimeout function, but as I've created the function passing the parameter as current element, I'm unable to get it.
Here's the pen.
Any help will be much appreciated.
Thanks!
You had several problems there:
The setTimeout function must be called upon display (and not upon build), otherwise it can be called even before you display the notification (hence your notification will not be automatically removed).
When you call the setTimeout in order to destroy the notification - you need to pass the container of the notification you just created, so the destroy function will be able to find the relevant element to remove (when you use the click option - you pass the X element, so it's easy to find the closest container, but when you use the setTimeout you must pass the container element himself).
I think all of the changes I made are in the build function, here it is:
Notification.prototype.build = function() {
var self = this;
var closeHTML = self.options.autoClose ? '' : '';
if (self.options.type == 'thumb') {
var $notificationHTML = $('<div class="notification-container">' +
'<i class="close">x</i>' +
'<div class="notification">' +
'<div class="thumb-container">' +
'<img src="' + self.options.src + '">' +
'</div>' +
'<p>' + self.options.text + '</p>' +
'</div>' +
'</div>');
} else {
var $notificationHTML = $('<div class="notification-container">' +
'<i class="close">x</i>' +
'<div class="notification ' + self.options.style + '">' +
'<p>' + self.options.text + '</p>' +
'</div>' +
'</div>');
}
self.$body.prepend($notificationHTML);
if(self.options.autoClose) {
setTimeout(function() {
self.destroy($notificationHTML);
}, 5000)
} else {
self.$body.on('click', '.close', function() {
self.destroy(this);
})
}
};
And a working codepen:
http://codepen.io/anon/pen/JKgPgB?editors=0010

Javascript Magento Create Account Preference Error

I am trying to create a second action on the Create New User Account form on Magento 1.9CE. We need an additional action to build an HTTP string and send to a URL as configured. So far we have built a script to pick up the fields, but this javascript isn't processing because the VarienForm is attached the event handler on document load. Could anybody shed some light on this code we have as to why its not processing?
<script type="text/javascript">
$(document).ready(function() {
window.setTimeout(function() {
$('#form-validate').on('submit', function( e )
{
var elements = this.elements;
e.preventDefault();
e.stopPropagation();
var subscribed = elements.is_subscribed.checked ? "y" : '';
var bglink = "http://suite9.emarsys.net/u/register_bg.php?owner_id=428212131&f=1481&key_id=3&optin=" + subscribed + "&inp_1=" + elements.firstname.value + "&inp_2=" + elements.lastname.value + "&inp_3=" + elements.email_address.value + "&inp_4=" + elements.year.value + "-" + elements.month.value + "-" + elements.day.value;
var img = $('<img width="1" height="1" src="'+bglink+'">')
.on('load error', $.proxy(function()
{
HTMLFormElement.prototype.submit.apply(this);
}, this))
.appendTo(this);
return false;
});
}, 2000);
});
</script>
If you are using jquery in your website may be jquery and prototype are conflict, to fix it:
- first of all you shoud add jQuery.noConflict(); to your website
- the second replace $ equal jQuery
ex:jQuery(document).ready(function() { })

Jquery Json not working properly

I have the following which works fine:
$('<li><a id=' + loc.locId + ' href="/DataEntry" rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");
$("#btnList a").click(function () {
alert(siteName);
localStorage["dataEId"] = $(this).attr("id");
localStorage["dataESiteName"] = siteName;
localStorage["dataESysName"] = sysName;
localStorage["dataELocName"] = $(this).text();
}
When I have the following, I can't even get to the click to display an alert message:
$.getJSON('/Home/GetLocType', { "locId": loc.locId }, function (result) {
var str = JSON.stringify(result);
if (str == '1') {
$('<li><a id=' + loc.locId + ' href="/DataEntry" rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");
} else {
$('<li><a id=' + loc.locId + ' href="/DataEntry/PotableForm" rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");
}
$("#btnList").listview('refresh');
});
$("#btnList a").click(function () {
alert(siteName);
localStorage["dataEId"] = $(this).attr("id");
localStorage["dataESiteName"] = siteName;
localStorage["dataESysName"] = sysName;
localStorage["dataELocName"] = $(this).text();
}
Note sure what the difference is. I need to use Json as based on value, I need to go to a either of the 2 hyperlinks.
Use event delegation since anchor is created dynamically in your ajax call or bind the event (only for the added element) inside the ajax success callback. on syntax will work if your jquery version >= 1.7 for earlier versions take a look at live
$("#btnList").on('click', 'a', function () {
alert(siteName);
localStorage["dataEId"] = $(this).attr("id");
localStorage["dataESiteName"] = siteName;
localStorage["dataESysName"] = sysName;
localStorage["dataELocName"] = $(this).text();
}
Your first syntax works because it binds the click event to the anchor that exists underneath btnList, but it doesn't bind event to the ones added during the ajax calls in a later point in time.

jQuery animation order before/after load

I am trying to slide my main container #main up before loading the new content inside and then slide down again when the load is complete. This seems to work on the first click but on subsequent clicks the content loads instantly before the slideUp and slideDown animations begin.
$("#access a").address(function() {
$("div#main").slideUp(1111).delay(1200).load($(this).attr('href') + ' #menudropdown, #contentbody', function(){
$("div#main").slideDown(1111);
});
var current = location.protocol + '//' + location.hostname + location.pathname;
if (base + '/' != current) {
var diff = current.replace(base, '');
location = base + '/#' + diff;
}
});
Have you tried:
$("#access a").address(function() {
var mainDiv = $("div#main");
var loadLink = $(this).attr('href');
mainDiv.slideUp(1111,function(){
mainDiv.load( loadLink + ' #menudropdown, #contentbody', function(){
mainDiv.slideDown(1111);
});
});
// your other code
});
Have you tried the ready event on slideUp?
$("div#main").slideUp(1111, function () {
$(this).load($("#access a").attr('href') + ' #menudropdown, #contentbody', function(){
$("div#main").slideDown(1111);
});
});
Also I would suggest to hide the content before loading by using the full ajax function:
$.ajax({
url: $("#access a").attr('href'),
success: function (data) {
$("div#main").slideUp(function () {
$(this).hide().empty().append(data.find('#menudropdown, #contentbody')).slideDown();
});
}
});

Click handlers on links not working

I have a chrome extension in which I have
popup.html where I call jquery.js, popup.js and link.js
...
<script src="jquery.js"></script>
<script src="popup.js"></script>
<script src="link.js"></script>
</head>
popup.js
var streamGenerator = {
/* Twitch URL to the top 20 streams */
searchOnTwitch_: 'https://api.twitch.tv/kraken/streams?limit=20',
/* XHR Request to grab those streams */
requestStreams: function() {
var req = new XMLHttpRequest();
req.open("GET", this.searchOnTwitch_, true);
req.onload = this.showStreams_;
req.send(null);
},
/* onload event inserting the streams into the DOM */
showStreams_: function(e) {
var streams = JSON.parse(e.target.responseText).streams;
for (var i=0; i < streams.length; i++) {
var stream = {
game: streams[i].game,
name: streams[i].channel.name,
viewers: streams[i].viewers,
link: streams[i].channel.url,
};
$('tbody').append('<tr>'
+ '<td>' + stream.game + '</td>'
+ '<td>' + '<a href=' + stream.link + '>' + stream.name + '</a></td>'
+ '<td>' + stream.viewers + '</td></a>'
);
}
}
};
document.addEventListener('DOMContentLoaded', function() {
streamGenerator.requestStreams();
});
and then link.js
$(function() {
$('a').click(function(){
chrome.tabs.create({url: $(this).attr('href')});
});
})
The popup works and show what it is supposed to show, but the links don't open a new tab.
If I go to chrome's console, I don't get any error, but if I copy/paste the link.js jquery, the links work after;
What am I doing wrong?!
Your code loads popup.js before link.js. The relevant parts are executed in the following order:
// popup.js
$(function() {
$('a').click( ... );
})
// link.js
document.addEventListener('DOMContentLoaded', function() {
streamGenerator.requestStreams(); //<-- Creates the links
});
$(func) is roughly equal to document.addEventListener('DOMContentLoaded', func), so what you're doing is actually something like:
// Run after the DOMContentLoaded "domready" event:
$('a').click(...);
streamGenerator.requestStreams(); // Creates the links
First, you're binding the click event to all existing anchors (none). Hereafter you're adding the new links. This sequence is obviously not going to work.
It can be solved by swapping the order of popup.js and link.js, or by using event delegation:
$(document).on('click', 'a', function() {
chrome.tabs.create({url: this.href});
});

Categories

Resources