How to open a new browser tab from within a jQuery callback - javascript

I have tried the following to achieve this:
Jquery Open in new Tab (_blank)
How can I open a link in a new window?
But neither works when calling window.open from inside the callback. Here's my code
$.post('api', {
}, function() {
var win = window.open('target-file', '_blank');
win.focus();
});

Try this:
$.post('api', {
}, function() {
window.open('target-file', '_blank');
});

try it with the name of the window
Like
window.open("url", "NameOfNewWindow");
SEE HERE

use MySurfaceWindow = window.open("url","windowname","settings");
see below example:
MySurfaceWindow = window.open('/DesktopModules/DMS/DMS.PatientEChart/Surface Pages/Surface6.aspx?SurfaceTooth=' + $("#lbl" + $(this).val()).text() + '&ProcedureID=0' + '&ColorD=I' + '', '', 'height=240,width=200,top=' + top + ',left=' + left + 'status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=no');

ou can add this simple jQuery snipplet to your source to open every external link in a new tab of the web browser
$(document).ready(function(){
$('a').each(function() {
var a = new RegExp('/' + window.location.host + '/');
if(!a.test(this.href)) {
$(this).click(function(event) {
event.preventDefault();
event.stopPropagation();
window.open(this.href, '_blank');
});
}
});
});

Related

Dynamically adding multiple events to multiple webviews

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();

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();
});
}
});

Adding variable at the end of URL using jQuery

So far I have done
jQuery:
function addURL(element)
{
var baseZipCode = 48180;
$(element).attr('href', function() {
return this.href + baseZipCode;
});
}
html:
<a onclick="addURL(this)" href="http://www.weather.com/weather/today/" target="_blank">Click this</a>
My problem is when user clicks on link and the new window open everything is ok, but when the user clicks on the link again without a refresh, the variable is added twice to the link.
For example:
First time:
http://www.weather.com/weather/today/48180
Second time:
http://www.weather.com/weather/today/4818048180
It doesn't act right until you do a page refresh, any help would be appreciated. Thanks in advance
Replace your addURL function with
function addURL(element)
{
var baseZipCode = '48180';
if (element.href.slice(-baseZipCode.length) !== baseZipCode){
element.href += baseZipCode;
}
}
there is no jQuery involved..
You can try it with jQuery.fn.one
Javascript:
jQuery("a").one("click", function(){ // Set a handler that execute once
var baseZipCode = 48180;
this.href += baseZipCode; //same as "this.href = this.href + baseZipCode"
});
HTML:
Click this
Maybe you will need to add some class to <a> tags to differ it from another ones
This should be:
function addURL(element)
{
var baseZipCode = 48180;
element.href = (element.href + baseZipCode)
.replace(baseZipCode + baseZipCode, baseZipCode);
}
return this.href.indexOf(baseZipCode) != -1 ? this.href : this.href + baseZipCode;

how to dynamically alter the hash location un a url based on link clicks

I have this working with just one instance of links, but I wanted to consolidate my code and re-use the same snippet for each instance of links.
Presently I have working:
$("nav a").live('click', function(){
window.location.hash = '!/' + usr + '/' + $(this).attr("href").replace('.php', '/');
origHash = $(this).attr("href");
return false;
});
$("#files-left-pane a").live('click', function(){
window.location.hash = '!/' + usr + '/files/' + $(this).attr("href").replace('.php', '/');
origHash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function(){
dump = window.location.hash;
newHash = window.location.hash.substring(3).replace(usr + '/', '').replace('/', '.php');//.replace('files/', '');
//newHash = window.location.hash.replace(dump, origHash, 'g');
console.log(newHash);
if (newHash) {
$wrap.find("#main-content").fadeOut(200, function() {
$wrap.load(newHash + " #main-content", function() {
$content.fadeIn(function() {
$wrap.animate({
height: baseHeight + $content.height() + "px"
}, 500);
});
});
});
}
});
right now, if a user clicks on $("nav a") it will make window.location.hash look like this
(in this example the user clicks on Files)
www.site.com/#!/s2xi/files/
the $(window).bind('hashchange') will then translate the hash into
www.site.com/files.php
Then, if a user clicks on $("#files-left-pane a") which is in a sub menu located in files.php. The window.location.hash will look like this :
(in this example the user clicks on Buy)
www.site.com/#!/s2xi/files/buy/
the $(window).bind('hashchange') should then translate the hash into
www.site.com/buy.php
If all you want is take the last word and add ".php", thats easy
You have two ways for that, i think the easiest one is split (the other one is regex).
var splittedHash = window.location.hash.split("/")
newHash = splittedHash[splittedHash.length - 2] + ".php";
Should easily do the trick.
By the way, the regex version is:
newHash = window.location.hash.match(/[^\/]*\/$/)[0].replace("/","") + ".php"

Check if popup window is already open

How can I modify this so it checks and if a popup window is already open?
function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=350,height=100');");
}
/////////////Edit No2
var options = "toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=350,height=100";
var popup = window.open(URL, "popup", options);
function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=350,height=100');");
}
My js call
<a id="floating_link" href="javascript:popUp('MyPage.html')">Player</a>
Use the same id for the window, which is the name of the window, to reuse it if it exists.
http://www.w3schools.com/jsref/met_win_open.asp
var options = "toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1,width=350,height=100";
var popup = window.open(URL, "popup", options);
To do this with an anchor tag you just set the target
If you set an anchor tag's target target="myopup" it will use that same window if it exists
My answer is to this question linked to here.
Check the following code.
You can use onbeforeunload to get a callback before the window unloads.
To check if this is due to window.close do this
setTimeout(function(){
if(anc.closed) console.log('closed');
else console.log('refreshed');
},1000); // to check after the window closed
FULL CODE
var anc = window.open('https://stackoverflow.com');
var anc.onbeforeunload = function() { // called before closing the window.
setTimeout(function() {
if (anc.closed) console.log('closed');
else console.log('refreshed');
}, 1000); // to check after the window closed
}

Categories

Resources