Unable to open a url in chrome and sfari - javascript

I am using openModal() javascript function ,its working fine in ie ,but in chrome and safari its appending base url with url i am sending,resulting in an error? Please Help!!
function OpenModalReplyDialog(url, SubscriberId) {
//Todo: Cleanup the unnecessary code.
var returnValue = new ModalReturnValue(null, null, null);
var retVal = null;
var urlredirect = url + '/UC_5_0_0.aspx?SubscriberId=' + SubscriberId;
returnValue = openModal(urlredirect, 350, 500);
return true;
}
This is code for openModal()
function openModal(url, width, height, args, options)
{
var returnValue = new ModalReturnValue(null, null, null);
var dialogArguments = self;
var defaultWindowOptions = 'center:yes;status:no;unadorned:yes;help:no;resizable:yes;';
if(args !=null)
{
dialogArguments = args;
}
var windowOptions = 'dialogHeight:' + height + 'px;dialogWidth:' + width + 'px;' + (options != null ? options : defaultWindowOptions);
returnValue = window.showModalDialog(url, dialogArguments, windowOptions);
if (returnValue != null)
{
if (returnValue.Command == "TimeOut") {
if (pageSessionTimeoutInfo != null) {
if (pageSessionTimeoutInfo.IsModal) {
closeModal(returnValue);
return;
}
}
redirectToUrl(returnValue.Url);
}
else
return returnValue;
}
else
return returnValue;
}

window.showModalDialog() is deprecated, it’s removed by Chrome & Firefox etc but works in IE. Please consider other options like Jquery dialog or bootstrap dialog or HTML5 dialog element. window.showModalDialog polyfill using a dialog element, click here for details.

Related

CEFSharp RegisterExtension not working

I had an screen scraper app that used CEFSharp that was working fine until I updated CEFSharp to the latest version. It appears that the way I was registering javascript extension functions no longer works. Here is my startup code:
[STAThread]
public static void Main()
{
try
{
CefSettings settings = new CefSettings();
settings.RegisterExtension(new CefExtension("showModalDialog", Resources.showModalDialog));
//Perform dependency check to make sure all relevant resources are in our output directory.
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
ProcessCommandLine();
var browser = new BrowserForm("https://www.google.com");
Application.Run(browser);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
If I comment out the settings.RegisterExtension line, it runs fine. It used to work. Here is the code for my extension:
(function () {
absolutePath = function (href) {
var link = document.createElement("a");
link.href = href;
return (link.protocol + "//" + link.host + link.pathname + link.search + link.hash);
}
showModalDialog = function (url, arg, opt) {
url = url || ''; //URL of a dialog
arg = arg || null; //arguments to a dialog
opt = opt || 'dialogWidth:300px;dialogHeight:200px'; //options: dialogTop;dialogLeft;dialogWidth;dialogHeight or CSS styles
var caller = showModalDialog.caller.toString();
var dialog = document.body.appendChild(document.createElement('dialog'));
dialog.setAttribute('style', opt.replace(/dialog/gi, ''));
dialog.innerHTML = '×<iframe id="dialog-body" name="dialog-body" src="' + absolutePath(url) + '" style="border: 0; width: 100%; height: 100%;"></iframe>';
//document.getElementById('dialog-body').contentWindow.dialogArguments = arg;
document.getElementById('dialog-close').addEventListener('click', function (e) {
e.preventDefault();
dialog.close();
});
document.getElementById('dialog-body').addEventListener('load', function (e) {
this.style.height = this.contentWindow.document.body.scrollHeight + 'px';
this.style.width = this.contentWindow.document.body.scrollWidth + 'px';
this.contentWindow.close = function () {
dialog.close();
};
this.contentWindow.dialogArguments = arg;
this.window = this.contentWindow;
});
dialog.showModal();
//if using yield
if (caller.indexOf('yield') >= 0) {
return new Promise(function (resolve, reject) {
dialog.addEventListener('close', function () {
var returnValue = document.getElementById('dialog- body').contentWindow.returnValue;
document.body.removeChild(dialog);
resolve(returnValue);
});
});
}
//if using eval
var isNext = false;
var nextStmts = caller.split('\n').filter(function (stmt) {
if (isNext || stmt.indexOf('showModalDialog(') >= 0)
return isNext = true;
return false;
});
dialog.addEventListener('close', function () {
var returnValue = document.getElementById('dialog-body').contentWindow.returnValue;
document.body.removeChild(dialog);
//nextStmts[0] = nextStmts[0].replace(/(window\.)?showModalDialog\(.*\)/g, JSON.stringify(returnValue));
//eval('{\n' + nextStmts.join('\n'));
});
throw 'Execution stopped until showModalDialog is closed';
};
})();
Did something change about the syntax of extensions?
https://bugs.chromium.org/p/chromium/issues/detail?id=665391
It's a Chrome thing and it doesn't look like they are going to fix it.

JQuery History.js plugin not replacing state of one page in both HTML4 and HTML5 browsers

I am using JQuery History.js plugin to enable History API in HTML5 browsers and emulate in HTML4 browsers. I am using Ajaxify script to implement this plugin. I changed this script a little as shown:
var History, $, document;
function PrepareVariables() {
History = window.History,
$ = window.jQuery,
document = window.document;
}
function InitHistory() {
// Prepare Variables
var
/* Application Specific Variables */
//contentSelector = '#content,article:first,.article:first,.post:first',
contentSelector = '#navcontent';
$content = $(contentSelector), //.filter(':first'),
//contentNode = $content.get(0),
$menu = $('#menu,#nav,nav:first,.nav:first').filter(':first'),
activeClass = 'active selected current youarehere',
activeSelector = '.active,.selected,.current,.youarehere',
menuChildrenSelector = '> li,> ul > li',
completedEventName = 'statechangecomplete',
/* Application Generic Variables */
$window = $(window),
$body = $(document.body),
rootUrl = History.getRootUrl(),
scrollOptions = {
duration: 800,
easing: 'swing'
};
// Ensure Content
if ($content.length === 0) {
$content = $body;
}
// Internal Helper
$.expr[':'].internal = function (obj, index, meta, stack) {
// Prepare
var
$this = $(obj),
url = $this.attr('href') || '',
isInternalLink;
// Check link
isInternalLink = url.substring(0, rootUrl.length) === rootUrl || url.indexOf(':') === -1;
// Ignore or Keep
return isInternalLink;
};
// HTML Helper
var documentHtml = function (html) {
// Prepare
var result = String(html)
.replace(/<\!DOCTYPE[^>]*>/i, '')
.replace(/<(html|head|body|title|meta|script)([\s\>])/gi, '<div class="document-$1"$2')
.replace(/<\/(html|head|body|title|meta|script)\>/gi, '</div>');
// Return
return $.trim(result);
};
// Ajaxify Helper
$.fn.ajaxify = function () {
// Prepare
var $this = $(this);
// Ajaxify
//$this.find('a:internal:not(.no-ajaxy)').click(function (event) {
$this.find("a[data-isnav='0']").click(function (event) {
// Prepare
var
$this = $(this),
url = $this.attr('href'),
title = ($this.attr('title') || null);
// Continue as normal for cmd clicks etc
if (event.which == 2 || event.metaKey) {
return true;
}
// Ajaxify this link
History.pushState(null, title, url);
event.preventDefault();
return false;
});
// Chain
return $this;
};
// Ajaxify our Internal Links
$body.ajaxify();
// Hook into State Changes
$window.bind('statechange', function () {
// Prepare Variables
var
State = History.getState(),
url = State.url,
relativeUrl = url.replace(rootUrl, '');
// Start Fade Out
// Animating to opacity to 0 still keeps the element's height intact
// Which prevents that annoying pop bang issue when loading in new content
$content.animate({
opacity: 0
}, 800);
// Ajax Request the Traditional Page
callAjax("GetContent", {
URL: url /*typeOfHeader: contentType, argsdata: argdata*/
},
false,
function () {
var ops = $('#ops');
if (ops != null) ops.html('');
ShowProgress('');
//var now = (new Date()).getTime(); //Caching
//if (headerCache.exist(url)) {
// tDiff = now - headerCacheTime;
// if (tDiff < 3000) {
// setContentData(headerCache.get(url));
// return true;
// }
//}
},
function (d) {
//headerCache.set(url, d, null);
//cacheName = url;
HideProgress();
setContentData(d);
}, null);
// end ajax
}); // end onStateChange
}
(function (window, undefined) {
// Prepare our Variables
PrepareVariables();
// Check to see if History.js is enabled for our Browser
if (!History.enabled) {
return false;
}
// Wait for Document
$(function () {
InitHistory();
});
// end onDomLoad
})(window); // end closure
function UpdateHistory() {
var title = (document.title.trim().length > 0 ? document.title : null);
var url = window.location.href.replace(/^.*\/\/[^\/]+/, '');
var History = window.History;
History.replaceState(null, title, url);
$('a[data-isnav="0"').click(function () {
// Prepare
var
$this = $(this),
url = $this.attr('href'),
title = ($this.attr('title') || null);
// Continue as normal for cmd clicks etc
if (event.which == 2 || event.metaKey) {
return true;
}
// Ajaxify this link
History.pushState(null, title, url);
event.preventDefault();
return false;
});
}
function setContentData(d) {
var data = d.data;
// Fetch the scripts
//$scripts = $dataContent.find('.document-script');
//if ($scripts.length) {
// $scripts.detach();
//}
// Fetch the content
contentHtml = data;
if (!contentHtml) {
document.location.href = url;
return false;
}
// Update the menu
//$menuChildren = $menu.find(menuChildrenSelector);
//$menuChildren.filter(activeSelector).removeClass(activeClass);
//$menuChildren = $menuChildren.has('a[href^="' + relativeUrl + '"],a[href^="/' + relativeUrl + '"],a[href^="' + url + '"]');
//if ($menuChildren.length === 1) { $menuChildren.addClass(activeClass); }
// Update the content
$content.stop(true, true);
$content.html(contentHtml).ajaxify().css('opacity', 100).show(); /* you could fade in here if you'd like */
//Intialize other content
initContent();
// Update the title
//document.title = $data.find('.document-title:first').text();
//try {
// document.getElementsByTagName('title')[0].innerHTML = document.title.replace('<', '<').replace('>', '>').replace(' & ', ' & ');
//}
//catch (Exception) { }
// Add the scripts
//$scripts.each(function () {
// var $script = $(this), scriptText = $script.text(), scriptNode = document.createElement('script');
// if ($script.attr('src')) {
// if (!$script[0].async) { scriptNode.async = false; }
// scriptNode.src = $script.attr('src');
// }
// scriptNode.appendChild(document.createTextNode(scriptText));
// contentNode.appendChild(scriptNode);
//});
// Complete the change
if ($body.ScrollTo || false) {
$body.ScrollTo(scrollOptions);
} /* http://balupton.com/projects/jquery-scrollto */
$window.trigger(completedEventName);
// Inform Google Analytics of the change
if (typeof window._gaq !== 'undefined') {
window._gaq.push(['_trackPageview', relativeUrl]);
}
// Inform ReInvigorate of a state change
if (typeof window.reinvigorate !== 'undefined' && typeof window.reinvigorate.ajax_track !== 'undefined') {
reinvigorate.ajax_track(url);
// ^ we use the full url here as that is what reinvigorate supports
}
}
It is working fine and the content added on page using Ajax is added to previous state using UpdateHistory() function. On some pages the state is updated successfully but on one page it is not updating the content when the page is accessed for the second time. I searched SO for all the similar questions but unable to get any solution. First I thought the problem is with Internet Explorer but then I tried it on Firefox but it didn't work. Please tell me what can be the reason?
UPDATE
It's working for URLs like:
http://localhost:13956/AppStore/App/2012/Install
But not for:
http://localhost:13956/AppStore
It's look like first page is not saved. Try to call UpdateHistory() or History.pushState(null, title, url) inside InitHistory().

Overriding XMLHttpRequest's open/send method

I am trying to catch every XHR Request send from Gmail and add a classification lable in the body of the mail. I am not sending new XHR requests. My code is working like filter for all XHR requests by overriding XMLHttpRequest's open/send function. I am working on this issue from last week.Please help me.
function sendEmail() {
//alert("In sendEmail()");
var overrideMethods = function() {
//alert("In overrideMethods()");
window.XMLHttpRequest.prototype._open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
this.openParams = {
url: url
};
return window.XMLHttpRequest.prototype._open.apply(this, arguments);
};
window.XMLHttpRequest.prototype._send = XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function send() {
var defered = false;
var searchPattern = /(&selectedLable=|^selectedLable=)(.*?)&/;
alert("In send()");
if (typeof arguments[0] === "string" && arguments.length === 1) {
var str = arguments[0];
//alert("Inside of first if");
//alert("str : " + str);
if (this.openParams.url.match(/&act\=sm/) && str.match(/&bcc\=/) && str.match(searchPattern)) {
defered = true;
var sendData = (str.match(searchPattern) && str.match(searchPattern)[2]);
var tag = JSON.parse(decodeURIComponent(sendData)).tag;
alert("tag : " + tag);
/* Modify the POST url to reflect the tag */
str = str.replace(searchPattern, "");
str = str.replace(/&subject=/, "&subject=" + tag + ": ");
str = str.replace(/&body\=/, "&body=<br>" + tag.toLowerCase() + "<br>");
/* Capitalize the tag. */
arguments[0] = str + "&acn=!" + tag.charAt(0).toUpperCase() + tag.slice(1).toLowerCase();
window.XMLHttpRequest.prototype._send.apply(this, arguments);
}
}
if (!defered) { 
window.XMLHttpRequest.prototype._send.apply(this, arguments);
}
};
}
window.location.href = 'javascript: (' + overrideMethods.toString().replace(/(\n|\ {2,})/gm, '') + ')();';
}
sendEmail();
I found this link on stack overflow :
Overriding XMLHttpRequest's send method
Please note my method is working fine for native chrome extension, but its not working for crossrider extension.

jQuery indexOf error for xdomain.js cross-domain link script

I'm using a script to detect cross-domain links for google analytics cross-domain tracking. The original script (xdomain.js) was provided by the great folks at Luna Metrics. Here is the script with my modifications, hat-tip to educardocereto here on StackOverflow for the suggested changes to enable setAllowAnchor in the GATC (I've commented line 40 where the console error first points to):
var jQueryXD = jQuery.noConflict();
/* I added var because page loads 2 versions
of jquery - not the source of the problem.*/
function listenToClicks()
{
var domains=["domain1.com", "domain2.com"];
var fileTypes=[".pdf"];
jQueryXD('a').each(function(index) {
var link = jQueryXD(this);
var href = link.attr('href');
jQueryXD.each(fileTypes, function(i) {
if(jQueryXD(link).attr('href').indexOf(this)!=-1){ //this is line 40
valid = false;
jQueryXD(link).bind('click', function(c) {
c.preventDefault();
_gat._getTrackerByName()._trackEvent('Download', 'Click - ' + jQueryXD(link).attr('href'));
setTimeout('document.location = "' + jQueryXD(link).attr('href') + '"', 100);
});
}
});
var valid = false;
jQueryXD.each(domains, function(j) {
try
{
if((jQueryXD(link).attr('href').indexOf(this)!=-1)&&(window.location.href.indexOf(this)==-1)){
valid = true;
if (valid)
{
jQueryXD(link).bind('click', function(l) {
if(typeof(_gat)=="object"){
l.preventDefault();
if (jQueryXD(link).attr('target') != "_blank")
{ // _gaq.push(['_link',jQueryXD(link).attr('href')]);
_gaq.push(['_link',jQueryXD(link).attr('href'), true]); // mod
}
else
{
var tracker = _gat._getTrackerByName();
//var fullUrl = tracker._getLinkerUrl(jQueryXD(link).attr('href'));
var fullUrl = tracker._getLinkerUrl(jQueryXD(link).attr('href'), true); //mod
window.open(fullUrl);
}
}
});
}
}
}
catch(e)
{
//Bad A tag
}
});
var rootDomain = document.domain.split(".")[document.domain.split(".").length - 2] + "." + document.domain.split(".")[document.domain.split(".").length - 1];
if ( (href.match(/^http/)) && (href.indexOf(rootDomain) == -1) && !valid) {
jQueryXD(link).bind('click', function(d) {
d.preventDefault();
_gat._getTrackerByName()._trackEvent('Outbound Link', href);
setTimeout('document.location = "' + href + '"', 100);
});
}
});
}
jQueryXD(document).ready(function() {
listenToClicks();
});
The output from the Chrome javascript console:
Uncaught TypeError:
Cannot call method 'indexOf' of undefined xdomain-nfi-nfs-anchormod-noconflict.js:40
jQueryXD.each.valid xdomain-nfi-nfs-anchormod-noconflict.js:40
jQuery.extend.each jquery-1.2.6.min.js:21
(anonymous function) xdomain-nfi-nfs-anchormod-noconflict.js:39
jQuery.extend.each jquery-1.2.6.min.js:21
jQuery.fn.jQuery.each jquery-1.2.6.min.js:12
listenToClicks xdomain-nfi-nfs-anchormod-noconflict.js:35
(anonymous function) xdomain-nfi-nfs-anchormod-noconflict.js:100
jQuery.fn.extend.ready jquery-1.2.6.min.js:27
jQuery.extend.ready.jQuery.readyList jquery-1.2.6.min.js:27
jQuery.extend.each jquery-1.2.6.min.js:21
jQuery.extend.ready jquery-1.2.6.min.js:27
So, atleast it seems to be not mixing up the two jquery instances. I've also tried it with jquery 1.7.1. I'm using 1.2.6 because the script seems to have been moste tested on that version.
Here you cache both the jQuerified element and the href attr.
var link = jQueryXD(this);
var href = link.attr('href');
Than why do you later do this:
jQueryXD(link).attr('href').indexOf(this)
You could either call link.attr('href').indexOf(this) since link is already a jQuery object or you could use directly the href you cached and do this href.indexOf(this).
Still I think the error you see happens when a link doesn't have an href attribute. So you better check if the href is not undefined before continuing your logic.
I tested it on both jQuery 1.2.6 and 1.7. It seems to be working fine.
Here's the finished script.
var jQueryXD = jQuery.noConflict();
/* I added var because page loads 2 versions
of jquery - not the source of the problem.*/
function listenToClicks() {
var domains = ["domain1.com", "domain2.com"];
var fileTypes = [".pdf"];
jQueryXD('a').each(function(index) {
var link = jQueryXD(this);
var href = link.attr('href');
if(!href){
// This element doesnt have a href
return true;
}
var valid = false;
jQueryXD.each(fileTypes, function(i) {
if (href.indexOf(this) != -1) { //this is line 40
valid = false;
link.bind('click', function(c) {
c.preventDefault();
_gat._getTrackerByName()._trackEvent('Download', 'Click - ' + link.attr('href'));
setTimeout('document.location = "' + href + '"', 100);
});
}
});
jQueryXD.each(domains, function(j) {
try {
if ((href.indexOf(this) != -1) && (window.location.href.indexOf(this) == -1)) {
valid = true;
if (valid) {
link.bind('click', function(l) {
if (typeof(_gat) == "object") {
l.preventDefault();
if (link.attr('target') != "_blank") { // _gaq.push(['_link',jQueryXD(link).attr('href')]);
_gaq.push(['_link', href, true]); // mod
}
else {
var tracker = _gat._getTrackerByName();
//var fullUrl = tracker._getLinkerUrl(href);
var fullUrl = tracker._getLinkerUrl(href, true); //mod
window.open(fullUrl);
}
}
});
}
}
}
catch (e) {
//Bad A tag
}
});
var rootDomain = document.domain.split(".")[document.domain.split(".").length - 2] + "." + document.domain.split(".")[document.domain.split(".").length - 1];
if ((href.match(/^http/)) && (href.indexOf(rootDomain) == -1) && !valid) {
jQueryXD(link).bind('click', function(d) {
d.preventDefault();
_gat._getTrackerByName()._trackEvent('Outbound Link', href);
setTimeout('document.location = "' + href + '"', 100);
});
}
});
}
jQueryXD(document).ready(function() {
listenToClicks();
});
But you might be reinventing the wheel here. There are some better scripts out there to achieve the same thing. I think you might be interested in looking into GAS. It's a wrapper around ga.js that extends and add a bunch of stuff including crossDomain and downloadTracking.
Spoiler: I'm the main developer of GAS.
https://github.com/CardinalPath/gas

window.open create reference to the name based

This way I get the reference to the open window:
var refWin = window.open("mypage1", "name_mypage");
if you want to close the window, I close with:
refWin.close();
if I do a screen refresh (F5) and run the same line, it opens in the same window, because I put the same name.
var refWin = window.open("mypage2", "name_mypage");
but with different reference (refWin).
Question: how I can make reference to the window based on the name?, I need to close the window before opening, with the same name.
do something like:
var refWin = window.open("about:blank", "name_mypage");
refWin.close();
refWin = window.open("mypage2", "name_mypage");
but without having to be a blank window for reference.
thanks
Based on andres's comment, here is the solution he's looking for:
refWin.location = "myurl";
refWin.focus();
This will open "myurl" in the window, and focus it.
Or.
var refWin = window.open("mypage1", "name_mypage");
refWin.focus();
Edit:
If you're not reloading the page again, there shouldn't be any reason you can't just do this:
var refWin = window.open("mypage1", "name_mypage");
refWin.close();
refWin = window.open("mypage1", "name_mypage");
If you're really concerned about it, you could make your own "windows" object:
var windows = {};
var refWin = window.open("mypage1", "name_mypage");
windows[refWin.name] = refWin;
windows("name_mypage").close(); // close the window
I don't think that's terribly productive, as you still can't focus it reliably, but maybe it fits your uses.
my solution based on another script:
Helper.window = new function () {
// Private fields
var w = window, s = screen, _self = this, whs = {}, isChrome = /chrome/.test(navigator.userAgent.toLowerCase());
// Public Members
this.focus = function (wh) {
if (!wh) return;
if (isChrome) wh.blur();
wh.focus();
};
this.windowExists = function (wt) {
return wt && whs[wt] && (typeof whs[wt]['closed'] != undefined) && !whs[wt].closed;
};
this.close = function (wt) {
if (typeof whs[wt][close] != undefined) whs[wt].close();
whs[wt] = null;
return _self;
};
this.properties = function (wp) {
wp = (wp || 'menubar=yes').toLowerCase();
if (!(/menubar/.test(wp)))
wp += 'menubar=yes';
if (!(/location/.test(wp)))
wp += ',location=yes';
if (!(/width/.test(wp)))
wp += ',width=' + (s.availWidth - 150);
if (!(/height/.test(wp)))
wp += ',height=' + (s.availHeight - 150);
if (!(/scrollbars/.test(wp)))
wp += ',scrollbars=yes';
if (!(/resizable/.test(wp)))
wp += ',resizable=yes';
return wp;
};
this.open = function (url, wt, wp) {
if (_self.windowExists(wt))
return _self.close(wt).open(url, wt, wp);
var urlOpen = '';
if (typeof url == 'string') {
urlOpen = url;
} else if (jQuery(url).get(0).tagName.toLowerCase() == 'a') {
urlOpen = jQuery(url).attr('href');
} else {
urlOpen = 'about:blank';
}
wp = _self.properties(wp);
wt = wt || "_blank";
var wh = wp ? w.open(urlOpen, wt, wp) : w.open(urlOpen, wt);
if (wh && "_blank" !== wt) {
whs[wt] = wh;
_self.focus(wh);
}
return wh;
};
};

Categories

Resources