SuityeCRM - jQuery Code not working On Chrome - javascript

$("#subpanel_title_documents").click(function(){
alert("clicked");
alert("loaded");
$("#documents_cases_create_button").click(function(){
alert("clicked");
setTimeout(function(){console.log("undefined");},1000);
alert("test");
setTimeout(function(){
if($("#account_id").attr("data-id-value") != ""){
alert("account");
setTimeout(function(){
var idAccount = $("#account_id").attr("data-id-value");
var nAccount = $("#account_id").text();
alert(idAccount);
alert(nAccount);
$("#account_id_c").val(idAccount);
$("#accounts_c").val(nAccount);
},500);
}else{
$("#subpanel_title_contacts").click();
alert("subpanel open");
setTimeout(function(){
var idcontact = $("*[data-module='Contacts']").data("record-id");
var nomecontact = $("*[data-module='Contacts']").data("module-name");
alert(idcontact);
alert(nomecontact);
$("#contact_id_c").val(idcontact);
$("#contacts_c").val(nomecontact);
$("#Documents_subpanel_full_form_button").click();
},1500);
};
},1000);
});
});
I'm trying to populate some fields on SuiteCRM after some actions.
This code works well on Mozilla Firefox but not on Google Chrome. After second Alert ( alert("loaded") ) stops working on Chrome.
Can anyone understand what is the issue?

You should include some more details, like in which module/detail view/edit vew/popup are you trying this.
For instance in the account module this ID documents_cases_create_button doesn't exist.
Furthermore, I haven't found evidence that this documents_cases_create_button exists in the SuiteCRM official repo.
If you are doing something custom, please specify.
also, if you are loading content using AJAX, and that AJAX is executed at the same time that $("#subpanel_title_documents").click(function(){ is Clicked, then the DOM object documents_cases_create_button might not be there quite yet.
If you don't know, the set a timeout before setting this listener
$("#subpanel_title_documents").click(function(){
console.log("Documents Clicked")
setTimeout(function(){
console.log("Just waited 3 secs for dom to finish loading AJAX content")
$("#documents_cases_create_button").click(function(){
console.log("I finally got the event I wanted");
})
},3000);
})
If that was the issue, then your option will be to set some kind of Observer. (thats what I do for AJAX loaded content when there are no native callbacks).

Related

window.focus doesn't work within http promise then

I try to make a focus on a new tab window , within callback (then function) of a http request and it doesn't work . i.e -
$http.get('').then(function () {
that.myWin.focus(); // isn't focusing
})
I did a demo for that , press "Open" to open the tab and then press "Focus" to focus in this tab which doesn't work .
Here is another demo which isn't within then that works fine .
How to make the focus function to work well ?
EDIT :
I'm testing on Google Chrome.
I know this is kind of wiered issue, on which spent my couple of hours and actually I found something working.
While debugging I found that if, we tries to focus tab for than 1 sec of time, It doesn't focus the tab. So I assumed that in one second I should access that.myWin object, otherwise after 1sec nothing happens with tab focusing.
$scope.focus = function() {
//maintained flag for checking promise completed or not.
var promiseResolved = false; //by default false
// on each second I'm checking promise has resolved or not.
var interval = setInterval(function() {
if (promiseResolved) {
console.log('Going to focus tab')
clearInterval(interval); //clearing interval
that.myWin.focus(); //focusing tab
}
}, 1000); // 1sec interval because of above assumption
//ajax call using $http
$http.get('').then(function() {
//set flag to true when promise resolved
promiseResolved = true;
console.log("I'm here");
});
};
I know I partially figured out what may be happening, but anyone can point out, if they find anything right/wrong in my answer. I'd appreciate that help. Thanks.
Demo Fiddle

JS not running until second refresh of page

Just what it says. I'm trying to do some simple drop down filtering with jquery, and my function doesn't get executed on page load. Here's what I've checked:
added a console.log to verify
used document.ready to call function
It's getting loaded through sprockets in app.js
it's listed in dev console, and I don't get any resource not found errors
Here's the crazy part : everything works perfectly after one refresh. Console.log comes back and reports the listener has been attached to the select element and everything is roses.
Any ideas why?
EDIT here's the entirety of the js (there may be a better way of doing this, also open to suggestions):
//unrelated JS
$(document).ready(function(){
$("#user_state_code option").unwrap();
$state_copy = $("#user_state_code").children().clone(true);
$("#user_country_code").change(function(){
console.log("state filter called");
filterStates($("#user_country_code").val());
});
$("#user_country_code").change();
});
function filterStates(countryCode){
$("#user_state_code").html(
$state_copy.get().filter(function(d){
var currCountry = String(d.value);
return currCountry.slice(0,2) == countryCode;
})
);
}
Epilogue
Here's what needed to be fixed (thanks to #Rain who put me in the right track, and prompted me to find this amazing resource: Rails 4 turbo-link prevents jQuery scripts from working
var ready = function() {
$("#user_state_code option").unwrap();
$state_copy = $("#user_state_code").children().clone(true);
$("#user_country_code").change(function(){
console.log("state filter called");
filterStates($("#user_country_code").val());
});
filterStates($("#user_country_code").val());
};
function filterStates(countryCode){
$("#user_state_code").html(
$state_copy.get().filter(function(d){
var currCountry = String(d.value);
return currCountry.slice(0,2) == countryCode;
})
);
}
$(document).ready(ready);
$(document).on('page:load', ready);

How to call a site's function from a Chrome extension?

I'm trying to make a Chrome extention for myself, so that when I visit any sort of channel at Twitch.tv, the chat will automatically hide.
I've been looking at it with Firebug and I found toggle_chat(). If I type that in the console, the chat is no longer visible.
In my userscript file, I have written
window.onload = function() {
toggle_chat();
}
but it says
Uncaught ReferenceError: toggle_chat is not defined" in the console when I load a Twitch channel.
Any ideas how to make this work?
This has nothing to do with timing. Chrome extensions and content scripts execute in an isolated world, meaning they have no access to the page's javascript including functions. You could make it so that your content script appends a <script> element that then calls the page function that you want but it would be far easier to just simulate a click on the #right_close element. You can do this with pure Javascript like this:
window.onload = function(){
var evObj = document.createEvent('Events');
evObj.initEvent('click', true, false);
document.querySelector('#right_close').dispatchEvent(evObj);
}
I know this is very hacky, but it gets the job done, and sometimes that exactly what you need. :) It'll check for the function roughly ever half second until it exists. When it's finally there, it'll call the function then clear the timer.
window.onload = function() {
var id = null;
var check = function() {
if (typeof toggle_chat === "function") {
toggle_chat();
clearInterval(id);
}
}
id = setInterval(check, 500);
}

Re-render a webpage

I was wondering if there was a way to render a webpage over again, thus calling all the onload events over again, and redrawing the css?
For example, say you changed the pathway of a javascript file that is linked to an onload event and the edited page needed to reload without a refresh in order for the change to take affect.
tested, now is working:
function fireEvent(element,event){
if (document.createEventObject){
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
else{
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}
setTimeout(function(){
var links = document.getElementsByTagName("link");
var st = [];
for(var x=0;x<links.length;x++)
if(links[x].getAttribute("rel") == "stylesheet")
{
st.push(links[x]);
links[x].wasAtt = links[x].getAttribute("href");
links[x].setAttribute("href", "");
}
setTimeout(function()
{
for(var x =0;x<st.length;x++)
st[x].setAttribute("href", st[x].wasAtt);
setTimeout(function(){
fireEvent(window, "load");
},1000);
},1000);
},5000); // test reload after five seconds
"reload without a refresh" sounds a bit confusing to me.
However I do not know if this is what you are looking for, but window.location.reload() triggers a page reload and thus will load your linked javascript files.
But changing linked files and reload the page is not a good thing to do. It would be better if your dynamic files are loaded in a dynamic way like using Ajax. So you do not need to reload the whole page. Frameworks like JQuery, ExtJS or others provide methods to do this easily.

Annoying Popup - (or other more graceful solution)

Here's my "need" - I have a user opening a window with a document displayed, I need to log the amount of time the user has that window "in focus" or "opened"... IF the user views another window, I want to stop logging the time - and resume logging if they re-focus on that page... basically I want to "know" how long it took a user to read the page.
this is a review type scenario, where the users is a 'trusted' member who needs to log their time... I want to keep a 'running total' for reference only - so if the user says that spent 10 min, on the page, but my log shows the window was only open for 2min, I know I've got a problem...either with my code or my people.. ;)
My thought was to keep a js counter going when the page was in focus, pause on blur or on close, and Ajax the data back to my db... and add any subsequent time to that record if the user returns...
onUnload doesn't seem to work, at least when i try - plus it doesn't catch a closing of the browser... so I was thinking I could launch a NEW window, when the document window is closed (not to be annoying - but to make the logging call to the server, and then close itself).
Does anyone have a solution for this? I know this all smacks of 'poor' design, but if someone has a 'correct' way to handle this scenario - please tell me. (BTW- IE is a requirement- it's intranet based IE7 req.)
Thx
======== sample code below - that is 'not' working...kinda ============
When i say it's NOT working, this is what I mean... The "XMLHttpRequest" Is being made, i assume because the response is the message I'd expect - HOWEVER the log isn't changes (I know you'll say it's the php page, but if I call the url directly - it works fine... so it's no the logging page, IN ADDITION the 60 second setInterval() seems to fire randomly, because my response alert just pops up, sometime 10 in a row with no time between, certainly not at 'regular' 60 sec intervals... THOUGHTS?
<script type="text/javascript">
var closeMe = 0;
var logMe = 0;
//the window doesn't have focus, do nothing or something that let's them know we're not logging at the moment
function onBlur() {
//after 2 min of non focus, close it.
closeMe = setInterval('window.close()',120000); //after 2 min of non focus, close it.
};
//the window has focus... keep logging.
function onFocus(){
//stop the close counter - in the event to 'blurred' sometime
clearInterval ( closeMe );
//run the AJAX on a schedule - we're doing it every minute - bu tyou can do it as often as you like
logMe = setInterval('logTime()',60000);
};
//call a script that logs another minute...
function logTime() {
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "ajax-on-time-interval.php", false);
xhReq.send(null);
var serverResponse = xhReq.responseText;
alert(serverResponse);
}
// check for Internet Explorer... IE uses 'onfocusin/out" - everything else uses "onfocus/blur"
if (/*#cc_on!#*/false) {
document.onfocusin = onFocus;
document.onfocusout = onBlur;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
}
</script>
I've have thought that a regular Ajax based "heartbeat" that updates the underlying database data every 'n' seconds (depending on the granularity you require, I'd have thought every minute would be sufficient) would be a neater solution than a pop-up and also avoid the fact that not all browsers handle onunload, etc. gracefully.
That said, I'm presuming that JavaScript will be enabled on these machines. (Seems fair based on your question.)
window.onfocus and onblur are documented in the MDC, but they're not standards. Evidently IE has document.onfocusin and .onfocusout :
if (/*#cc_on!#*/false) { // check for Internet Explorer
document.onfocusin = onFocus;
document.onfocusout = onBlur;
} else {
window.onfocus = onFocus;
window.onblur = onBlur;
}
I haven't tried it. I just read about it here.
http://www.thefutureoftheweb.com/blog/detect-browser-window-focus
One somewhat sloppy solution that partially resolves the issue with the browser closing/crashing is to have an ajax function that pings the server DB at a set interval while the document is in focus. This way, if the client crashes, you will be accurate within 30 seconds of how how long the document was open.

Categories

Resources