Part of the javascript is not running - javascript

The JS below runs accordingly, but it never hits the last function (showAllTabIdRedirect). Any idea why? Is it my syntax? I am trying to run the first function that grabs the primary tab id and then use that to pass along some other functions. In the end, I would redirect the user as well as refresh a specific tab.
<script>
function refreshDetailsTab() {
sforce.console.getEnclosingPrimaryTabId(focusDetailSubtabRedirect);
var formsId;
var currentUrl = window.location.href;
if (currentUrl) {
formsId = currentUrl.split('?formId=')[1];
} else {
return;
}
window.location = '/' + formsId;
debugger;
};
sforce.console.getEnclosingPrimaryTabId(focusDetailSubtabRedirect);
var focusDetailSubtabRedirect = function showTabIdRedirect(result) {
// window.onload = function showTabIdV1(result) {
//alert('2222');
var primaryTabID = result.id;
sforce.console.getSubtabIds(primaryTabID , showAllTabIdRedirect);
debugger;
}
var showAllTabIdRedirect = function showAllTabIdRedirect(result2) {
// alert('33333');
var firstSubTab = result2.ids[0];
sforce.console.refreshSubtabById(firstSubTab, false);
debugger;
//alert('Subtab IDs=====: ' + result.ids[0]);
};
window.onload = refreshDetailsTab;
</script>

You can check for successful completion of those methods. It's possible 'getSubtabIds' was at halt for some reason and that would cause the failure of calling the callback function 'showAllTabIdRedirect '.
See the documentation here for getSubtabIds

I think it has something to do with the window.location triggering first. It redirects the user before the other JS can load.

Related

window.onload function not running on refresh

I have an window.onload function that does not run when a user manually refreshes the page. I have noticed that on the page refresh, the URL is appended with a # at the end, but I don't know if that has anything to do with the error. The function correctly executes when first loaded, but not after a refresh.
window.onload = function() {
alert("HERE");
var a = document.getElementById("link1");
a.onclick = function() {
var current = window.location.href;
alert(current);
if (current.indexOf("&page=") != -1) {
current = current.substring(0,current.indexOf("&page="));
}
var nextPage = current + "&page=link1"
window.location.replace(nextPage);
return false;
}
}
UPDATE: It seems as though it is working in Chrome, but not Safari.
Also, additional information, my a tag looks like this:
<a id='link1' href='#'>Link 1</a>
try using :
$(document).ready(function() {
});
instead.
check if it helps..

Infinite loop when redirecting in Javascript

I have a sample page, let' say testpage.pl When I choose English version, GET parameter is added to URL, like /?language=en.
Afterwards, when I click menu positions, they are in the English version so everything is OK.
But if I want to have English version of a subpage directlty after pasting URL in a browser, like
http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html)
the Polish version is opened. So I've made a simple redirect function like below, but it comes to the loop after first start. This function redirect to the same page, but before it tries to redirect to this first URL with GET parameter ?language=en
How to solve this?
function cleanUrl() {
window.location = "http://testpage.pl/?language=en";
var cleanedUrl = "http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html";
var currentUrl = window.location.href;
if (currentUrl !== cleanedUrl) {
window.location = cleanedUrl;
}
}
cleanUrl();
Your are updating url in first line of function which is causing your code to loop infinite. Remove that line or move to some other function for fix
function cleanUrl() {
var cleanedUrl = "http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html";
var currentUrl = "http://testpage.pl/?language=en";
if (currentUrl !== cleanedUrl) {
window.location = cleanedUrl;
}
}
cleanUrl();
Keep the window.location assignment as last operation.
function cleanUrl() {
var enUrl = "http://testpage.pl/?language=en";
var cleanedUrl = "http://testpage.pl/wyjazdy-i-przyjazdy/erasmus-incoming-staff/accommodation.html";
var currentUrl = window.location.href;
if( currentUrl !== cleanedUrl ) { enUrl = cleanedUrl; }
window.location = enUrl;
}

Javascript setTimeout fires as many times in as page loaded by ajax

I am executing setTimeout function in a page which loads via ajax call. but if i click the link to load the page again, i afraid the last setTimeout call still continues and the number of intervals of the calls set by setTimeout executes multiple times.
tried this is the remote page:
var RefreshInterval = null;
clearTimeout(RefreshInterval);
function someFunction()
{
....
setNextRefresh();
}
function setNextRefresh() {
console.log(wifiRadarRefreshInterval);
RefreshInterval = null;
clearTimeout(RefreshInterval);
RefreshInterval = setTimeout('someFunction();', 20*1000);
}
declare var RefreshInterval = null; outside of page loaded by ajax and use this code on the page:
clearTimeout(RefreshInterval);
function someFunction()
{
....
setNextRefresh();
}
function setNextRefresh() {
console.log(wifiRadarRefreshInterval);
clearTimeout(RefreshInterval);
RefreshInterval = setTimeout('someFunction();', 20*1000);
}
if i don't want to declare it in parent page, here is the solution i found:
//Clear previously loaded calls if exists
try{ clearTimeout(wifiRadarRefreshInterval); }catch(e){}
var wifiRadarRefreshInterval = null;
function somefunction(){
....
setNextRefresh();
}
function setNextRefresh() {
try{
clearTimeout(wifiRadarRefreshInterval);
wifiRadarRefreshInterval = null;
wifiRadarRefreshInterval = setTimeout('somefunction();', 20*1000);
}
catch(e){
console.log(e.message + e.stack);
}
}
Do not use this
var RefreshInterval = null;
clearTimeout(RefreshInterval);
You are actually assigning a null and then trying to clear it. Which will not work, The timeout must be cleared by using the clearTimeout and by passing the variable which was assigned to the setTimeout. Here you will end up passing a null so the timer is never cleared.
Here is a small sample which will demonstrate a fix to your problem JS Fiddle
So insted of setting the variable to null and then trying to clear it, Just check if the variable is not defined and if it is defined clear it, else move on. Use the code below, Also you must remove the top two lines as mentioned
function setNextRefresh() {
console.log(wifiRadarRefreshInterval);
if (typeof RefreshInterval !== 'undefined') {
clearTimeout(RefreshInterval);
}
RefreshInterval = setTimeout('someFunction();', 20*1000);
}
Click on the button say like 4 times, The output should be printed only once. That is if the ajax call is made 4 times the set time out must execute only once. Check below snippet for demo
var clickCount= 0; // just to maintain the ajax calls count
function NewPageSimilator(clicksTillNow) { // this acts as a new page. Let load this entire thing on ajaX call
if (typeof RefreshInterval !== 'undefined') {
clearTimeout(RefreshInterval);
}
function setNextRefresh() {
window.RefreshInterval = setTimeout(printTime, 3000); //20*1000
}
function printTime() {// dumy function to print time
document.getElementById("output").innerHTML += "I was created at click number " + clicksTillNow + '<br/>';
}
setNextRefresh();
}
document.getElementById("ajaxCall").addEventListener("click", function() { // this will act as a ajax call by loading the scripts again
clickCount++;
NewPageSimilator(clickCount);
});
document.getElementById("clear").addEventListener("click", function() { //reset demo
clickCount = 0;
document.getElementById("output").innerHTML = "";
});
<p id="output">
</p>
<button id="ajaxCall">
AJAX CALL
</button>
<button id="clear">
Clear
</button>

History.pushState creates large amout of entries

I'm trying to create something like a dynamic page, but I have this problem. When I fire history.pushState it creates large amount of history entries, even though the action that fires it is run only once. My code is as follows:
var url = 'http://localhost:8888/depeche-mode/violator'; // example url
var plainUrl = url + '/?plain',
startUrl = 'http://localhost:8888/',
newUrl = url.replace(startUrl, '#/');
$('#content').animate({
opacity: 0
}, 250, function() {
$('#content').load(plainUrl +' #content > *', function(response) {
$('#content').animate({opacity:1}, 250, function() {
document.title = pageTitle;
Posts.historyHash(newUrl);
});
});
});
edit:
var Posts = {
historyHash: function(newUrl) {
window.location.hash = newUrl;
$(window).bind('hashchange', function() {
var url = window.location.hash,
nohash = url.replace('#',''),
properUrl = 'http://localhost:8888/'+nohash;
history.pushState('','',newUrl);
});
}
}
The problem is very serious when I want to use Back button in my browser - I need to click it couple of times before I actually get to change the url. What can I do?
You're calling historyHash when you load content, and historyHash registers an event handler on window — every time you call it. So you end up with a bunch of event handlers for the hashchange event.
You presumably only want one. Either just register one, or unregister the previous ones when registering a new one.
I can't quite tell which of those you want, but as the handler uses the newUrl, it may well be that you want to unregister previous handlers. If so, probably best to use an event namespace so you only unregister your own handlers:
var Posts = {
historyHash: function(newUrl) {
window.location.hash = newUrl;
$(window)
.unbind('hashchange.historyhash') // Out with the old
.bind('hashchange.historyhash', function() { // In with the new
var url = window.location.hash,
nohash = url.replace('#',''),
properUrl = 'http://localhost:8888/'+nohash;
history.pushState('','',newUrl);
});
}
}
Although looking at it, you could just use a single handler and remember newUrl on Posts:
var Posts = {
historyHash: function(newUrl) {
window.location.hash = newUrl;
this.newUrl = newUrl;
}
};
$(window).bind('hashchange', function() {
var url, nohash, properUrl;
if (Posts.newUrl) {
url = window.location.hash,
nohash = url.replace('#',''),
properUrl = 'http://localhost:8888/'+nohash;
history.pushState('','',Posts.newUrl);
}
});

"Unable to load http://url status:0" error in onbeforeunload-method

may someone of you can help me to find this problem?
I've got an xpage with client-side js-code included which should be executed when you decide to leave the page. In the client-side js you refer to a button and click it automatically. This button got some server-side js code included and change the flag from a document from ("opened by ..." to "").
The thing is that somehow the client-side js did not work in all different browsers except the current IE (10.0.5) and throws the error:
unable to load http://urlofthedocument/... status:0
The funny thing about this is, when I insert an alert()-method right after the click()-method everything works fine in every browser. But as I don't want to include this alert statement I figure out there must be something different to avoid this. (A short pause instead of the alert-method also did not work.)
My CS JS-Code:
window.onbeforeunload = WarnEditMode;
function WarnEditMode(){
if(needUnloadConfirm == true){
var el = window.document.getElementById("#{id:Hidden4SSJS}");
el.click();
//document.open();
//document.write(el);
//document.close();
//alert("You're about to leave the page");
//pause(5000);
}
}
function pause(millis){
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < millis)
}
This refers to to button, which executes following SS JS code, after it is clicked:
try{
print("Hidden4SSJS-Button-Test # Person");
var db:NotesDatabase = database;
var agt:NotesAgent;
var doc:NotesDocument = XPPersonDoc.getDocument()
agt = db.getAgent("(XPUnlockDocument)");
agt.run(doc.getNoteID());
}catch(e){
_dump(e);
}
May you guys can help me with this?
I would do this using the XSP object with a hidden computed field (and not your special button)...
Something like this:
function WarnEditMode(){
if(needUnloadConfirm == true){
XSP.partialRefreshGet("#{id:unlockDocCF1}", {
params: {
'$$xspsubmitvalue': 'needToUnlock'
},
onComplete: function () {
alert('You are about to leave this page and the document has been unlocked.');
},
onError : function (e) {
alert('You are about to leave this page and the document has NOT been unlocked.\n' + e);
}
);
}
pause(5000);
}
Then the computed field's javascript would be something like this:
try{
var sval = #Explode(context.getSubmittedValue(), ',');
if (sval == null) return result + " no action.";
if (!"needToUnlock".equals(sval[0])) return result + " no action.";
print("Hidden4SSJS-Button-Test # Person");
var db:NotesDatabase = database;
var agt:NotesAgent;
var doc:NotesDocument = XPPersonDoc.getDocument()
agt = db.getAgent("(XPUnlockDocument)");
agt.run(doc.getNoteID());
return 'document unlocked.';
}catch(e){
_dump(e);
}

Categories

Resources