Why is the title and favicon of the window/tab not updating? - javascript

I'm playing around with jetpack to change the title (and ideally the favicon) of certain pages.
Firebug is showing that the HTML of the page has been changed correctly but Firefox just won't update the title of the window and/or tab.
This has to be possible, somehow, since Twitter Search is doing exactly that. It's updating the title as more search results show up, isn't it?
I guess I'm just missing something... any idea?
Example code as suggested in the comment:
function replaceTitle(doc)
{
if (doc.location.protocol == "http:" || doc.location.protocol == "https:")
{
var host=doc.location.host;
if(host.indexOf("stackoverflow.com")>=0)
{
var title=doc.getElementsByTagName("title")
console.log(title);
if(title)
{
var val=title[0];
if(val)
{
console.log("val", val);
console.log("valx", val.textContent);
val.textContent="Foo";
console.log("valz", val.textContent);
}
}
}
}
}
var state = "on";
function toggleState()
{
if( state == "off" )
{
jetpack.tabs.onReady(replaceTitle);
state = "on";
}
else
{
jetpack.tabs.onReady.unbind(replaceTitle);
state = "off";
}
console.log(state);
// This is a temporary way of keeping all browser window states
// in sync. We are working on a better API for this.
/*
widgets.forEach(function(widget) {
widget.defaultView.wrappedJSObject.setState(state);
});
*/
}
jetpack.statusBar.append(
{
html: "Boo",
onReady: function(widget)
{
console.log("ready");
// This is a temporary way of keeping all browser window states
// in sync. We are working on a better API for this.
/*
widgets.push(widget);
widget.defaultView.wrappedJSObject.setState(state);
*/
$(widget).click(toggleState);
},
onUnload: function(widget)
{
console.log("unload");
/*
widgets.splice(widgets.indexOf(widget), 1);
*/
},
width: 42
});
console.log("Test");
Irritatingly, it doesn't even show logs anymore since jetpack and firebug have been updated in the meantime :p
I'd expect this code to replace the title of stackoverflow.com pages with "Foo" - but this is just an example, replace stackoverflow.com with anything else if that might help, i.e. probably a site with less javascript magic than SO.com.
Update:
I solved the problem with the help of the answer below.
The working example looks like this:
function replaceTitle()
{
var doc=this.contentDocument;
console.log("replaceTitle "+ doc);
if(doc)
{
var location = doc.location;
if ( (location.protocol == "http:" || location.protocol == "https:")
&& location.host.indexOf("stackoverflow.com") !== -1 )
{
doc.title = "Foo";
console.log("Title set to "+doc.title);
}
else
{
console.log("Location "+location);
}
}
}
var state = "on";
function toggleState()
{
if( state == "off" )
{
state = "on";
jetpack.tabs.onReady(replaceTitle);
}
else
{
state = "off";
jetpack.tabs.onReady.unbind(replaceTitle);
}
console.log(state);
}
jetpack.statusBar.append(
{
html: "Boo",
onReady: function(widget)
{
console.log("ready: "+state);
$(widget).click(toggleState);
},
onUnload: function(widget)
{
console.log("unload");
},
width: 42
});
console.log("Testing");

might want to try
function replaceTitle(doc)
{
var location = doc.location;
if ( (location.protocol == "http:" || location.protocol == "https:")
&& location.host.indexOf("stackoverflow.com") !== -1 ) {
document.title = "Foo";
}
}
works for me
http://pastebin.me/4a3550e0dbe19?framepage

if you back down to firebug 1.4.0b4 it will fix that console problem you're having.
http://groups.google.com/group/mozilla-labs-jetpack/browse_thread/thread/c0cba73c67f19530#

Related

custom when statement not firing functions

I am trying to make a when statement but it is not working as planned. Basically its a function to call another function when try. First before I explain further here is the syntax
when(function() {
//code here
});
Now basically... Think this way.. We have a progressbar.. We also have a custom event such as...
var pBarEvent = document.createEvent('Event');
pBarEvent.initEvent('pbardone', true, true);
document.addEventListener('pbardone', function() {
//code here
});
//if progress bar reaches 100 dispatchEvent
if (document.querySelector(".progress-bar").style.width === 100 + "%")
{
document.dispatchEvent(pBarEvent);
}
Now that piece of code is an example. If the document loads and its for instance at 50% it wont trigger until you add another event such as keydown or click. I dont want to do that I want to do.... "when" progress bar width equals 100% trigger it. Thats basically what needs to happen. So here is the code for the when statement so far (keep in mind its not the best looking one. As I dont normally do this but I wanted to keep this dynamic and who knows someone who later wants to do this can look at this question)
when function
function when(func)
{
var nowActive = false;
if (!typeof func === 'undefined')
{
func = new Function();
}
if (func)
{
nowActive = true;
clearInterval(whenStatementTimer);
}
else
{
nowActive = false;
var whenStatementTimer = setInterval(function() {
switch(func)
{
case true:
{
nowActive = true;
when();
break;
}
case false:
{
nowActive = false;
when();
break;
}
}
}, 1000);
}
if (nowActive === true)
{
func();
}
}
Now this does not work when I go to try something like....
when(function() {
SmartLeadJS.SmartLeadEvents.customEvents.progressBarFull(function() {
alert("100%");
SmartLeadJS.SmartLeadAds.LeadView.ChromeExtension.General.DynamicStyles.$.style("body", "background", "black");
});
});
It does not trigger. I need help possibly getting this when statement to work. What am I doing wrong? What can I do to fix it? No errors get thrown but it never fires.
edit based on answer
Function tried
function when(currentValue)
{
try
{
var o = {};
o.currentValue = currentValue;
o.do = function(func)
{
if (!typeof func === 'undefined')
{
func = new Function();
}
if (this.currentValue)
{
func();
}
else
{
setTimeout(this.do(func), 100);
}
};
return o;
}
catch(e)
{
console.log(e);
}
}
used as
when(true).do(function() {
SmartLeadJS.SmartLeadEvents.customEvents.progressBarFull(function() {
alert("This divs going through changes!!");
SmartLeadJS.SmartLeadAds.LeadView.ChromeExtension.General.DynamicStyles.$.style(".div", "background", "black");
});
});
This does not work. It never fires. But if I use a onclick listener as such it fires
document.addEventListener("click", function() {
SmartLeadJS.SmartLeadEvents.customEvents.progressBarFull(function() {
alert("This divs going through changes!!");
SmartLeadJS.SmartLeadAds.LeadView.ChromeExtension.General.DynamicStyles.$.style(".div", "background", "black");
});
}, false);
function when(statement){
o={};
o.statement=statement;
o.do=function(func){
awhen(this.statement,func);
};
return o;
}
function awhen(statement,func){
if(eval(statement)){
func();
}else{
window.setTimeout(function(){awhen(statement,func);},100);
}
}
Use:
when("true").do(function(){});
It works now :) . Its important to put the condition in ""!

Show a div only once per visit / set cookie

I'm trying to set an element so it's being shown only once per visit. It's a scroll down arrow on my homepage and so once the user gets it it won't be necessary to keep it anymore. So I don't want it to be shown while the user is surfing on my website however, when he visits it again in the future it's there again. I'm a newbie and can't quite solve it.
My code:
setTimeout(function () {
$('.scroll_down').show()
}, 2000);
var $element = $('.scroll_down'); // fade out / in on scroll
$(window).scroll(function() {
if($(this).scrollTop() > 0) {
$element.fadeOut(1000);
}
});
I also would like the arrow to fade in but my attempts were not successful. Thanks guys
Please write cookie code as follow:
jQuery(document).ready(function($){
if($.cookie('show_div_once') != 'yes'){
your_code_for_show_div;
}
$.cookie('show_div_once', 'yes', { path: '/', expires: 365 });
});
I used localStorage
firstSiteLoad = (function() {
var checkSupport;
checkSupport = function() {
var e, error, support;
try {
support = 'localStorage' in window && (window['localStorage'] != null);
} catch (error) {
e = error;
support = false;
}
return support;
};
return function() {
if (!checkSupport()) {
return false;
}
if (localStorage.getItem("not_first_load")) {
return false;
} else {
localStorage.setItem("not_first_load", 'true');
return true;
}
};
})();
you can use it by if (firstSiteLoad()) { //your code }

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.

javascript/jquery onClick make browser go Fullscreen [duplicate]

This question already has an answer here:
fullscreen through javascript
(1 answer)
Closed 9 years ago.
I am looking for a way of creating a button, when clicking on it the browser should go Fullscreen. *THIS SHOULD BE BUTTON.
Please, any ideas!
I found this similar post, i guess this is the solution!
onclick go full screen But ill come back later to this question, hope someone has a new solution!
You can't. There is no way to automatically go fullscreen. Instead, you can instruct/request that your users press F11 to go fullscreen manually, but it should be optional.
well here i what I found, it works but not sure for cross-browser support!
<div id="specialstuff" style="display: none;">
</p><p>Status: <span id="fsstatus" class="fullScreenSupported">Back to normal</span></p>
</div>
<input type="button" value="Go Fullscreen" id="fsbutton">
<script>
/*
Native FullScreen JavaScript API
-------------
Assumes Mozilla naming conventions instead of W3C for now
*/
(function() {
var
fullScreenApi = {
supportsFullScreen: false,
isFullScreen: function() { return false; },
requestFullScreen: function() {},
cancelFullScreen: function() {},
fullScreenEventName: '',
prefix: ''
},
browserPrefixes = 'webkit moz o ms khtml'.split(' ');
// check for native support
if (typeof document.cancelFullScreen != 'undefined') {
fullScreenApi.supportsFullScreen = true;
} else {
// check for fullscreen support by vendor prefix
for (var i = 0, il = browserPrefixes.length; i < il; i++ ) {
fullScreenApi.prefix = browserPrefixes[i];
if (typeof document[fullScreenApi.prefix + 'CancelFullScreen' ] != 'undefined' ) {
fullScreenApi.supportsFullScreen = true;
break;
}
}
}
// update methods to do something useful
if (fullScreenApi.supportsFullScreen) {
fullScreenApi.fullScreenEventName = fullScreenApi.prefix + 'fullscreenchange';
fullScreenApi.isFullScreen = function() {
switch (this.prefix) {
case '':
return document.fullScreen;
case 'webkit':
return document.webkitIsFullScreen;
default:
return document[this.prefix + 'FullScreen'];
}
}
fullScreenApi.requestFullScreen = function(el) {
return (this.prefix === '') ? el.requestFullScreen() : el[this.prefix + 'RequestFullScreen']();
}
fullScreenApi.cancelFullScreen = function(el) {
return (this.prefix === '') ? document.cancelFullScreen() : document[this.prefix + 'CancelFullScreen']();
}
}
// jQuery plugin
if (typeof jQuery != 'undefined') {
jQuery.fn.requestFullScreen = function() {
return this.each(function() {
var el = jQuery(this);
if (fullScreenApi.supportsFullScreen) {
fullScreenApi.requestFullScreen(el);
}
});
};
}
// export api
window.fullScreenApi = fullScreenApi;
})();
</script>
<script>
// do something interesting with fullscreen support
var fsButton = document.getElementById('fsbutton'),
fsElement = document.getElementById('specialstuff'),
fsStatus = document.getElementById('fsstatus');
if (window.fullScreenApi.supportsFullScreen) {
fsStatus.innerHTML = 'YES: Your browser supports FullScreen';
fsStatus.className = 'fullScreenSupported';
// handle button click
fsButton.addEventListener('click', function() {
window.fullScreenApi.requestFullScreen(fsElement);
}, true);
fsElement.addEventListener(fullScreenApi.fullScreenEventName, function() {
if (fullScreenApi.isFullScreen()) {
fsStatus.innerHTML = 'Whoa, you went fullscreen';
} else {
fsStatus.innerHTML = 'Back to normal';
}
}, true);
} else {
fsStatus.innerHTML = 'SORRY: Your browser does not support FullScreen';
}
</script>

Page Reload for Opera

I'm trying to get this page reload function to work in the new Opera v12. The function allows you to click away from a page & then come back and at that point the page is reloaded with a clean cache, ie fresh. What do I need to change to get it to work for Opera?
window.onload = function() {
var rel = document.getElementById('forme').toBeReloaded.value; //get the current var value
if (rel==1) { // retrieved from the server (reloaded)
if ($.browser.webkit || $.browser.msie) {
window.location.reload(); //loaded from the cache
}
if ($.browser.mozilla) {
buttonPlace();
console.log('Firefox Reload: ');
}
if ($.browser.opera) {
window.location.reload(true);
console.log('Opera Reload: ');
}
}
else {
document.getElementById('forme').toBeReloaded.value = 1;
}
}
Thanks, Bill
Figured it out using document ready and:
$(function() {
var rel = $('[name=toBeReloaded]');
if(rel.val() == 1) {
rel.val(0);
if ($.browser.opera) {
location.href = location.href; // reload
}
else {
location.href = location.href; // reload
}
}
else {
rel.val(1);
}
});
Bill

Categories