Only run JavaScript in Chrome - javascript

So I have a little script that only seems to work correctly in Chrome. It's not a big problem, however the negative effects it has in other browsers is annoying, so I'd like to only run it in Chrome.
This is my current working script that runs in all browsers:
function psn() {
var myElement = document.getElementById('noti');
if(window.addEventListener) {
// Normal browsers
myElement.addEventListener('DOMSubtreeModified', contentChanged, false);
} else
if(window.attachEvent) {
// IE
myElement.attachEvent('DOMSubtreeModified', contentChanged);
}
function contentChanged() {
// this function will run each time the content of the DIV changes
document.getElementById('audiotag1').play();
var vid = document.getElementById("audiotag1");
vid.volume = 1;
}}
setTimeout(function () {psn()}, 2000);
And this is what I've tried already to make it run only in Chrome, which made the script stop working all together:
function psn() {
var myElement = document.getElementById('noti');
if(window.addEventListener) {
// Normal browsers
myElement.addEventListener('DOMSubtreeModified', contentChanged, false);
} else
if(window.attachEvent) {
// IE
myElement.attachEvent('DOMSubtreeModified', contentChanged);
}
function contentChanged() {
// this function will run each time the content of the DIV changes
document.getElementById('audiotag1').play();
var vid = document.getElementById("audiotag1");
vid.volume = 1;
}}
var isChrome = !!window.chrome;
if (isChrome) {
setTimeout(function () {psn()}, 2000);
}
Anyone know why this is just stopping everything completely?

It is best to not have to do specific browser detection, but an easy way to see if you are using Chrome or not is the following:
var isChrome = navigator.userAgent.toLowerCase().indexOf("chrome") >= 0 ? true : false;
This will populate isChrome with either true of false.

Related

JS - Window Focus and Bring to front in Firefox

I am trying to set up a tiny script for Firefox that runs in a javascript add-on (Greasemonkey). We have a queue that we monitor for arriving tickets, I coded something that is supposed to refresh the page every 2 minutes and do the following:
if tickets are found by this condition
if (isEmpty($('#incident_table > tbody'))&isEmpty($('#task_table > tbody')))
then I want the following to happen:
- task-bar blinks with a message so it is visible
- if the window is focused it will display "Tickets in the queue!" alert right away
- if the window is not focused, it will wait for 10 seconds, if still not focused - display "Tickets in the queue!" alert and bring the window to front.
I've got the refresh and blinking part, but I cannot get the focus part to work... I've been looking around and I see that Firefox is having some "issues" with window.focus() and all the "bring to front", most of the code below is inspired by stuff I've found on this site.
Any input is appreciated! I am also opened to alternatives - in the end, what this needs to do is refresh, check the condition and notify if I am already looking at it or if it is not focused wait 10 seconds with a "soft notify" (blink) then bring it to the front if I don't notice it.
Regards,
Dan
{
newExcitingAlerts = (function () {
var oldTitle = document.title;
var msg = "***NEW***";
var timeoutId;
var blink = function() { document.title = document.title == msg ? 'Tickets in queue!' : msg; };
var clear = function() {
clearInterval(timeoutId);
document.title = oldTitle;
window.onmousemove = null;
timeoutId = null;
};
return function () {
if (!timeoutId) {
timeoutId = setInterval(blink, 1000);
window.onmousemove = clear;
}
};
}());
$(document).ready(function(){
function isEmpty( el ){
return !$.trim(el.html());
}
if (isEmpty($('#incident_table > tbody'))&isEmpty($('#task_table > tbody'))) {
}
else{
newExcitingAlerts();
}
setTimeout(function() {
location.reload();
}, 120000);
});
}
Here is the alternative I've used, works like a charm. Web API notifications.
document.addEventListener('DOMContentLoaded', function () {
if (Notification.permission !== "granted")
Notification.requestPermission();
});
function notifyMe() {
if (!Notification) {
alert('Desktop notifications not available in your browser. Try Chromium.');
return;
}
if (Notification.permission !== "granted")
Notification.requestPermission();
else {
var notification = new Notification('Tickets in queue!', {
icon: 'http://siliconangle.com/files/2014/05/servicenow-icon.png',
body: "There are new tickets in queue, please acknowledge!",
});
notification.onclick = function () {
window.open("https://cchprod.service-now.com/task_list.do?sysparm_query=assignment_group%3D3139519437b7f1009654261953990e1f^ORassignment_group%3D31de85e337818a00ef8898a543990e99^ORassignment_group%3Da40029e937ec420065aa261953990eb5^ORassignment_group%3De903ad2d37ec420065aa261953990ecb^ORassignment_group%3Dd25fe5323779c24065aa261953990e54^ORassignment_group%3D508639363779c24065aa261953990e29^ORassignment_group%3D51fe5a37379e0a00ef8898a543990ea2^ORassignment_group%3D3d8171b23779c24065aa261953990e21^ORassignment_group%3Decfe5a37379e0a00ef8898a543990e6c^ORassignment_group%3D48c0b9723779c24065aa261953990e5d^ORassignment_group%3De5fde9fe3739c24065aa261953990e75^ORassignment_group%3D15fe5a37379e0a00ef8898a543990e99^ORassignment_group%3D15fe5a37379e0a00ef8898a543990ea7^ORassignment_group%3D1ed3f1f23779c24065aa261953990e47^active%3Dtrue^sys_class_name%3Dincident^ORsys_class_name%3Dsc_req_item^assigned_toISEMPTY&sysparm_first_row=1&sysparm_view=");
};
}
}
{
newExcitingAlerts = (function () {
var oldTitle = document.title;
var msg = "***NEW***";
var timeoutId;
var blink = function() {
document.title = document.title == msg ? 'Tickets in queue!' : msg;
};
var clear = function() {
clearInterval(timeoutId);
document.title = oldTitle;
window.onmousemove = null;
timeoutId = null;
};
return function () {
if (!timeoutId) {
timeoutId = setInterval(blink, 1000);
window.onmousemove = clear;
}
};
}
());
$(document).ready(function () {
function isEmpty(el) {
return !$.trim(el.html());
}
var x = document.getElementById("task_table").getAttribute("grand_total_rows");
if( x != "0" ) {
newExcitingAlerts();
notifyMe();
}
else
{
}
setTimeout(function() {
location.reload();
}
, 120000);
});
}
In Windows operating system you cannot focus the window while the window of another process is focused. You have to use js-ctypes to get around this.
On Mac OS X and Linux, I'm not sure if you can make your process steal focus from another with the normal functions. But if you can't you can for sure use js-ctypes to get the job done.
Here is how to do it in Windows - https://stackoverflow.com/a/32038880/1828637
It is harder on Windows then on OS X and Linux. I have focused windows on all systems using js-ctypes. So if you can't find out how to do with the functions available to you, let me know.

How to use SyntaxHighlighter on a sharepoint 2013 blog (Office365)?

I'm trying to allow code highlighting using SyntaxHighlighter on a sharepoint 2013 blog site (office365 portal).
Here is the code I have put in the head of the masterpage (js and css ressources are loaded before) :
<script type="text/javascript">
function sh(){
SyntaxHighlighter.highlight();
};
// executed when SP load completes
_spBodyOnLoadFunctionNames.push("sh");
</script>
The _spBodyOnLoadFunctionNames should provide a mechanism to run functions after the load page event, but it seems it's never executed.
Running my sh function from the developper tool (console) is working as expected.
Does anybody have a clue, am I using the right event ?
_spBodyOnLoadFunctionNames array declared in init.js (it is a part of SharePoint JavaScript Library)
According to init.js:
AttachEvent("DOMContentLoaded", _spBodyOnLoadWrapper, document);
window.onload = _spBodyOnLoadWrapper;
where
function _spBodyOnLoadWrapper() {
ExecuteOrDelayUntilScriptLoaded(ProcessDefaultOnLoad, "core.js");
//the remaining code is omitted for clarity..
}
function ProcessDefaultOnLoad() {
ProcessOnLoadFunctionNames(_spBodyOnLoadFunctionNames);
//the remaining code is omitted for clarity..
}
function ProcessOnLoadFunctionNames(onLoadFunctionNames) {
if (onLoadFunctionNames != null) {
for (var i = 0; i < onLoadFunctionNames.length; i++) {
var expr = "if(typeof(" + onLoadFunctionNames[i] + ")=='function'){" + onLoadFunctionNames[i] + "();}";
eval(expr);
}
onLoadFunctionNames = [];
}
}
To summarize, the specified approach is a proper mechanism to run functions after the load page event.
In fact it works for me just fine (see the picture below)
Make sure init.js library is loaded before _spBodyOnLoadFunctionNames is initialized.
Alternatively you could try the following approach:
<script type="text/javascript">
function sh(){
SyntaxHighlighter.highlight();
};
ExecuteOrDelayUntilScriptLoaded(sh, "core.js");
</script>
Results
+Vadim Gremyachev's answer is valid with IE, but doesnt work with chrome, here is the workaround I've used (inspirated from https://stackoverflow.com/a/2956980/381149 ):
function sh(){
SyntaxHighlighter.highlight();
};
function setIntervalX(callback, delay, repetitions) {
var x = 0;
var intervalID = window.setInterval(function () {
callback();
if (++x === repetitions) {
window.clearInterval(intervalID);
}
}, delay);
}
$(document).ready(function () {
if( $('.syntaxhighlighter').length == 0 ){
setIntervalX(function() { sh() }, 1000,5);
}
$("a").on("click",function () {
if( $('.syntaxhighlighter').length == 0 ){
setIntervalX(function() {
sh()
}, 1000,5);
}
return true;
});
});

clearTimeout/setTimeout on mobile devices

I have to make a button that has the following functions:
If you click on it, it should show some lines and hide them after 3 seconds, but if you click on the button before the 3 seconds are over the lines should hide as well.
I have written some code that is working perfectly on desktop browsers, but on mobile browsers it is not. Android devices seem to ignore my clearTimeout and on iphones it seems more like a "buttonPressed" event.
I have created a jsfiddle so that you can see what i have written.
var timeout = null;
var buttonCallback = function() {
if( timeout === null ) {
log('show lines');
timeout = setTimeout(buttonCallback, 3000);
}
else {
clearTimeout(timeout);
timeout = null;
log('hide lines');
}
}
var hammerElement = Hammer(document.getElementById('showLines'));
hammerElement.on("touch", function(e) {
e.preventDefault()
buttonCallback();
});
Any idea how i can make this behaviour work for mobile browsers?
As #wumm mentioned, it works in my iPhone5 iOS7 as well.
Another way you could try is this fiddle I setup for you: http://jsfiddle.net/thePav/jC32X/5
HTML
<button id="showLines">Show Lines</button>
JS
var timeout;
var flag = false;
function buttonCallback() {
$('#showLines').click(function(){
if(flag == false){
flag = true;
//show lines here
timeout = setTimeout(function(){
flag = false;
//hide lines here
}, 3000);
}else{
flag = false;
clearTimeout(timeout);
//hide lines here
}
});
}
$(document).ready(function(){
buttonCallback();
});
Not sure what the issue with your code was but this is just another way to implement it.
The error was that on some mobile devices that I was testing (not all!) has sometimes send 2 tab events (double tab).
To fix that I have been added a delayTime and checked when the function got called last time.
var buttonCallback = function() {
if( timeout === null ) {
//for old slow andoid devices
if ((new Date().getTime() - delayTime) < 2200)
return;
delayTime = new Date().getTime();
log('show lines');
timeout = setTimeout(buttonCallback, 3000);
}
// for fast devices to prevent the double tab error
else if ( (new Date().getTime() - delayTime) > 1200 ) {
clearTimeout(timeout);
timeout = null;
log('hide lines');
}
}

Console.log Internet explorer 8 particular case [duplicate]

This question already has answers here:
'console' is undefined error for Internet Explorer
(21 answers)
Closed 8 years ago.
Hi i found the problem in other stackoverflow questions , the problem is i have tried all solutions that should work, but i think im not understanding where and how to implement that fixes..
My problem is console.log in internet explorer throws an error as undefined. I search and found
Console undefined issue in IE8
Internet Explorer: "console is not defined" Error
I try to wrap the code inside the function using a condition like 'if(window.console) '
this dosent work i even try most of the recommended contitions no one work, try to insert the snnipet in the code so it worked, but it dont..
Im obviously not understanding how and where to put does fixes. Sorry for my ignorance. but im in a hurry, need to someone points at my stupidity
Thanks
var jcount = 0;
var scroll_count = 0;
var playflag=1;
var ajxcallimiter=0;
var hp_totalcount=parseInt($("#hp_totalcount").val());
if(hp_totalcount<5)
hp_totalcount=5;
function hlist_slider()
{
if($(".items img").eq(jcount).length != 0 && playflag==1){
firedstyle();
console.log(jcount);
$(".items img").eq(jcount).trigger("mouseover");
if(jcount % 5 === 0 && jcount!=0)
{
console.log('scroll');
api.next();
scroll_count++;
}
jcount++; // add to the counter
if(jcount>hp_totalcount)
{
if(playflag==1)
{
jcount = 0; //reset counter
while(scroll_count--)
{
api.prev();
}scroll_count=1;
}
}
}
else if(jcount<hp_totalcount && playflag==1)
{
playflag=0;homepagelist_nextclick();playflag=1;
}
else
{
if(playflag==1)
{
jcount = 0; //reset counter
while(scroll_count--)
{
api.prev();
}
scroll_count=1;
}
}
}
$(function() {
var root = $(".scrollable").scrollable({circular: false}).autoscroll({ autoplay: true });
hlist_slider();
setInterval(hlist_slider,10000);
// provide scrollable API for the action buttons
window.api = root.data("scrollable");
});
function firedstyle()
{
$(".items img").on("hover",function() {
// see if same thumb is being clicked
if ($(this).hasClass("active")) { return; }
// calclulate large image's URL based on the thumbnail URL (flickr specific)
var url = $(this).attr("src").replace("t_", "");
var tbtit = $(this).siblings('.tbtit').text();
var tbdesc = $(this).siblings('.tbdescp').text();
var tbtitgoto = $(this).attr("data");
// get handle to element that wraps the image and make it semi-transparent
var wrap = $("#image_wrap").stop(true, true).fadeTo("medium", 0.5);
// the large image from www.flickr.com
var img = new Image();
// call this function after it's loaded
img.onload = function() {
// make wrapper fully visible
wrap.fadeTo("fast", 1);
// change the image
wrap.find("img").attr("src", url);
wrap.find(".img-info h4").text(tbtit);
wrap.find(".img-info p").text( tbdesc);
wrap.find("a").attr("href", tbtitgoto);
};
// begin loading the image from www.flickr.com
img.src = url;
// activate item
$(".items img").removeClass("active");
$(this).addClass("active");
// when page loads simulate a "click" on the first image
}).filter(":first").trigger("mouseover");
}
function toggle(el){
if(el.className!="play")
{
playflag=0;
el.className="play";
el.src='images/play.png';
//api.pause();
}
else if(el.className=="play")
{
playflag=1;
el.className="pause";
el.src='images/pause.png';
// api.play();
}
return false;
}
function hp_nxtclick()
{
homepagelist_nextclick();
console.log('scroll');
if(api.next()){
scroll_count++;}
}
function homepagelist_nextclick()
{
var hp_totalcount=parseInt($("#hp_totalcount").val());
var hp_count=parseInt($("#hp_count").val());
if(hp_totalcount==0 || hp_count >=hp_totalcount)
return ;
if(ajxcallimiter==1)
return;
else
ajxcallimiter=1;
$.ajax(
{
type: "GET",
url: "<?php echo $makeurl."index/homepageslide/";?>"+hp_count,
success: function(msg)
{
hp_count=parseInt($("#hp_count").val())+parseInt(5);
$("#hp_count").val(hp_count);
$("#hp_list").append(msg);ajxcallimiter=0;
}
});
}
The problem is that the console (developer tool panel) needs to be active on page-load*.
Hit F12, reload your page, and you should get what you're looking for.
*Just to clarify: The developer panel needs to be open prior to window.console being called/tested. I'm assuming your code is being run on-load.
This should work:
if(!window.console || !window.console.log) window.console = {log: function(){}};
This way you will be able to use console.log without producing errors.
In my code, I put this snippet at the top - before any other javascript that might try to use the console loads:
if (window.console == null) {
window.console = {
log: function() {},
warn: function() {},
info: function() {},
error: function() {}
};
}
Or in coffeescript:
if not window.console?
window.console = {
log: () ->
warn: () ->
info: () ->
error: () ->
}
This provides a dummy console for browsers that don't include one.

Jquery Fade In Fade Out Issue in Safari

I have created this simple image slider using jQuery:
Fiddle
I found that it runs perfectly in all the other browsers except for Safari in which it lags quite a bit.
Here's my code snippet of my script:
$(document).ready(function () {
loadLandingSlider();
});
var counter = 0;
function loadLandingSlider() {
totalImg = $('#rotating-item-wrapper img').length;
rotate = setInterval(function () {
loadImg();
}, 3000);
}
function loadImg() {
$('.rotating-item').fadeOut(1000);
$('#rot' + counter).fadeIn(1000);
if (counter == totalImg)
counter = 1;
else
counter++;
}
Is there some workaround for this?
Hi It doesn't lag in Safari (6.0.5) on OSX but your pictures are ways to big. 7 x 500kB is a lot of stuff to load and handle. Maybe this causes your lags.

Categories