I'm making a Chrome Exntesion and I'm wondering if I can have a predefined vaule to mathc the URL window.location.href
Currently my code looks like this;
chrome.tabs.getSelected(null, function(tab) {
if(window.location.href.indexOf("google") > -1) {
alert("This website is google");
} else {
alert("This website is not google");
}
However, it display it as not being google. Now I know that -1 if removed it always come up saying the website is google however, I'm not sure how to get round that.
Thanks,
Here is how to get a list of tabs that contains "google" in their url
chrome.tabs.query({}, (tabs) => {
var googleTabs = tabs.filter(tab => tab.url.indexOf("google") > -1);
// do logic on googleTabs which is of type Tab[]. link:
// https://developer.chrome.com/extensions/tabs#type-Tab
});
if you are just looking for the current tab you can use: https://developer.chrome.com/extensions/tabs#method-getCurrent
Related
Almost have it, but might need a hand :
I created a script to redirect AND set a cookie that comes in from ANY page from our site. So even if a user comes in from a direct link to a news article, it will redirect them to our "splash" page and set a "cookie" to avoid further redirects. I have that part working perfect.
$(document).ready(function() {
if (typeof Cookies.get('secondvisit') === 'undefined') {
window.location.href = "/index-donate.php";
}
})
However, we now want to capture the URL that they came to first and create a variable so we can have them be linked back to that page after they read our SPLASH page.
So in the example above:
Come in via direct link: /news/article1.php
No cookie is detected, so we first need to "capture" the page they came in on "$page-refer" and then redirect them to our Splash page.
On the splash page, we would then present a LINK to them with "Proceed to webpage" with the "$page-refer" link.
I did try this ( BELOW ), but this is only grabbing the "google" page and not OUR webpage that they hit first.
Thanks!
$(document).ready(function() {
if (typeof Cookies.get('secondvisit') === 'undefined') {
var referringURL = document.referrer;
var local = referringURL.substring(referringURL.indexOf("?"), referringURL.length);
location.href = "/index-donate.php" + local;
}
})
I think you could add the URL as a cookie when you do the redirect, ex:
$(document).ready(function () {
if (typeof Cookies.get('secondvisit') === 'undefined') {
Cookies.set('initialvisitedpage', window.location.href);
window.location.href = "/index-donate.php";
}
});
then you could redirect them to the cookie value:
$(document).ready(function() {
if (typeof Cookies.get('secondvisit') === 'undefined') {
window.location.href = Cookies.get('initialvisitedpage') || '/'; // or whatever this could default to in case they don't have the cookie
}
})
Put together an answer that works great, thanks for the comments and push:
On footer script template:
$(document).ready(function () {
if (typeof Cookies.get('secondvisit') === 'undefined') {
location.href = "/index-donate.php?page-refer=" + encodeURIComponent(location.href);
}
})
Then on my Splash page:
I captured the variable $pageredirect via $_GET['page-refer'] and then presented that as a link further down the page ( if set )!
I am currently developing a chrome extension that can get cookies from a website, using chrome.getCookies.
However, the url parameter in
chrome.getCookies
must be a static url in order to work, like this:
chrome.cookies.get({url: 'https://example.org/#/', name:
'token'}, function(cookie) {
document.getElementById("token").innerHTML = cookie.value
});
But I want to make that url changed dynamically based on which tab I am using that extension. So I tried this:
var tabUrl;
chrome.tabs.getSelected(null, function(tab) {
tabUrl = tab.url
});
chrome.cookies.get({url: tabUrl, name:
'token'}, function(cookie) {
document.getElementById("token").innerHTML = cookie.value
});
And it didn't work. What should I to to achieve my goal?
Edit: If anyone ever reach this page, here the solution, you have to put subsequent code inside the callback, here's the correct one:
chrome.tabs.getSelected(null, function(tab) {
chrome.cookies.get({url: tab.url, name: 'expa_token'}, function(cookie) {
document.getElementById("token").innerHTML = cookie.value
});
});
I have very weird requirement.
Requirement says: On Product detail page,when product image is opened in lightbox then on pressing back button on browser in mobile, product detail page shall be shown, not previous page i.e. product grid page
So, i thought of searching that how to handle back button in cross browsers. Some solutions worked in Desktop browsers but none worked in Mobile Browsers
I tried below solution:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
};
Also tried this:
if (window.history && window.history.pushState) {
$(window).on('popstate', function() {
var hashLocation = location.hash;
var hashSplit = hashLocation.split("#!/");
var hashName = hashSplit[1];
if (hashName !== '') {
var hash = window.location.hash;
if (hash === '') {
alert('Back button was pressed.');
}
}
});
Tried this as well
window.onbeforeunload = function (e) {
var e = e || window.event;
var msg = ""
$("#blueimp-gallery").hide();
// For IE and Firefox
if (e) {
e.returnValue = msg;
}
// For Safari / chrome
return msg;
};
As you've no doubt learned, onbeforeunload provides a way to simply cancel the navigation event (see this answer for a good place to start), but it doesn't always work the way you want in all browsers (many just show a confirmation popup no matter what you do, for security reasons). Give this a shot first if you haven't already; I don't see any attempts at cancellation in your current code example, just history manipulation.
Failing that, using hash routing might help with this - preferably via a library that manages the URL hash as unique view routes (baked into Angular, React, etc) and pushes changes to the history for you. Giving the modal state a unique URL (which typically wouldn't be done in my experience) means that going 'back' would just close the modal instead of reloading the page.
Rewriting the question -
I am trying to make a page on which if user leave the page (either to other link/website or closing window/tab) I want to show the onbeforeunload handeler saying we have a great offer for you? and if user choose to leave the page it should do the normal propogation but if he choose to stay on the page I need him to redirect it to offer page redirection is important, no compromise. For testing lets redirect to google.com
I made a program as follows -
var stayonthis = true;
var a;
function load() {
window.onbeforeunload = function(e) {
if(stayonthis){
a = setTimeout('window.location.href="http://google.com";',100);
stayonthis = false;
return "Do you really want to leave now?";
}
else {
clearTimeout(a);
}
};
window.onunload = function(e) {
clearTimeout(a);
};
}
window.onload = load;
but the problem is that if he click on the link to yahoo.com and choose to leave the page he is not going to yahoo but to google instead :(
Help Me !! Thanks in Advance
here is the fiddle code
here how you can test because onbeforeunload does not work on iframe well
This solution works in all cases, using back browser button, setting new url in address bar or use links.
What i have found is that triggering onbeforeunload handler doesn't show the dialog attached to onbeforeunload handler.
In this case (when triggering is needed), use a confirm box to show the user message. This workaround is tested in chrome/firefox and IE (7 to 10)
http://jsfiddle.net/W3vUB/4/show
http://jsfiddle.net/W3vUB/4/
EDIT: set DEMO on codepen, apparently jsFiddle doesn't like this snippet(?!)
BTW, using bing.com due to google not allowing no more content being displayed inside iframe.
http://codepen.io/anon/pen/dYKKbZ
var a, b = false,
c = "http://bing.com";
function triggerEvent(el, type) {
if ((el[type] || false) && typeof el[type] == 'function') {
el[type](el);
}
}
$(function () {
$('a:not([href^=#])').on('click', function (e) {
e.preventDefault();
if (confirm("Do you really want to leave now?")) c = this.href;
triggerEvent(window, 'onbeforeunload');
});
});
window.onbeforeunload = function (e) {
if (b) return;
a = setTimeout(function () {
b = true;
window.location.href = c;
c = "http://bing.com";
console.log(c);
}, 500);
return "Do you really want to leave now?";
}
window.onunload = function () {
clearTimeout(a);
}
It's better to Check it local.
Check out the comments and try this: LIVE DEMO
var linkClick=false;
document.onclick = function(e)
{
linkClick = true;
var elemntTagName = e.target.tagName;
if(elemntTagName=='A')
{
e.target.getAttribute("href");
if(!confirm('Are your sure you want to leave?'))
{
window.location.href = "http://google.com";
console.log("http://google.com");
}
else
{
window.location.href = e.target.getAttribute("href");
console.log(e.target.getAttribute("href"));
}
return false;
}
}
function OnBeforeUnLoad ()
{
return "Are you sure?";
linkClick=false;
window.location.href = "http://google.com";
console.log("http://google.com");
}
And change your html code to this:
<body onbeforeunload="if(linkClick == false) {return OnBeforeUnLoad()}">
try it
</body>
After playing a while with this problem I did the following. It seems to work but it's not very reliable. The biggest issue is that the timed out function needs to bridge a large enough timespan for the browser to make a connection to the url in the link's href attribute.
jsfiddle to demonstrate. I used bing.com instead of google.com because of X-Frame-Options: SAMEORIGIN
var F = function(){}; // empty function
var offerUrl = 'http://bing.com';
var url;
var handler = function(e) {
timeout = setTimeout(function () {
console.log('location.assign');
location.assign(offerUrl);
/*
* This value makes or breaks it.
* You need enough time so the browser can make the connection to
* the clicked links href else it will still redirect to the offer url.
*/
}, 1400);
// important!
window.onbeforeunload = F;
console.info('handler');
return 'Do you wan\'t to leave now?';
};
window.onbeforeunload = handler;
Try the following, (adds a global function that checks the state all the time though).
var redirected=false;
$(window).bind('beforeunload', function(e){
if(redirected)
return;
var orgLoc=window.location.href;
$(window).bind('focus.unloadev',function(e){
if(redirected==true)
return;
$(window).unbind('focus.unloadev');
window.setTimeout(function(){
if(window.location.href!=orgLoc)
return;
console.log('redirect...');
window.location.replace('http://google.com');
},6000);
redirected=true;
});
console.log('before2');
return "okdoky2";
});
$(window).unload(function(e){console.log('unloading...');redirected=true;});
<script>
function endSession() {
// Browser or Broswer tab is closed
// Write code here
alert('Browser or Broswer tab closed');
}
</script>
<body onpagehide="endSession();">
I think you're confused about the progress of events, on before unload the page is still interacting, the return method is like a shortcut for return "confirm()", the return of the confirm however cannot be handled at all, so you can not really investigate the response of the user and decide upon it which way to go, the response is going to be immediately carried out as "yes" leave page, or "no" don't leave page...
Notice that you have already changed the source of the url to Google before you prompt user, this action, cannot be undone... unless maybe, you can setimeout to something like 5 seconds (but then if the user isn't quick enough it won't pick up his answer)
Edit: I've just made it a 5000 time lapse and it always goes to Yahoo! Never picks up the google change at all.
I'm using the bit.ly url shortening service to shorten certain url's being sent to a "share on twitter" function. I'd like to load the bit.ly url only when a user actually presses the share button (due to bit.ly's max 5 parallel reqs limitation). Bit.ly's REST API returns a JSON callback with the shortened url, which makes the whole scenario async.
I've tried the following to stop the click event, and wait for the JSON call to return a value before launching the click.
I have the following simplified code in jQuery(document).ready():
Updated code (oversimplified)!
jQuery("#idofaelement").click(function(event) {
event.preventDefault(); //stop the click action
var link = jQuery(this);
bitlyJSON(function(shortUrl) {
link.attr("href", function() {
//process shortUrl
//return finalized url;
}).unbind().click();
});
});
And the following code to handle the bitly shortening (works just fine):
function bitlyJSON(func) {
//
// build apiUrl here
//
jQuery.getJSON(apiUrl, function(data) {
jQuery.each(data, function(i, entry) {
if (i == "errorCode") {
if (entry != "0") {
func(longUrl);}
} else if (i == "results") {
func(entry[longUrl].shortUrl);}
});
});
} (jQuery)
The href gets its value changed, but the final .click() event never gets fired. This works fine when defining a static value for the href, but not when using the async JSON method.
As you outlined yourself:
event.preventDefault(); //stop the click action
That means, BROWSER IS NOT GOING TO THAT URL, if you wish to actually go forward to the long-url location, simply do something like:
document.location.href = longurl;
iirc, jquery doesn't trigger "click" on A elements. I'd try old good "location.href=whatever" in the callback.
bitlyJSON(function(shortUrl) {
link.attr("href", function() {
//process shortUrl
//return finalized url;
});
location.href = link.attr("href");
});
I think what you actually want is to return false; from the click event, to prevent the actual following of the href, right?
Like:
jQuery("#idofaelement").click(function(event) {
//event.preventDefault(); //stop the click action
var link = jQuery(this);
bitlyJSON(function(shortUrl) {
link.attr("href", function() {
//process shortUrl
//return finalized url;
}).unbind().click();
});
return false;
});
#Tzury Bar Yochay pointed me in the right direction by suggesting I use location.href to update the url. Also #Victor helped with his answer.
I got things kinda working combining the answers, but had issues with the history in firefox. Seems that updating window.location indeed redirected the user, but also removed the "source page" from the history. This did not happen in chrome, safari, ie8, ie8-compatibility or ie7.
Based on this response to another question I was able to create a workaround giving the following working code + made a few changes:
jQuery("#idofaelement").one("click", function(event) {
bitlyJSON(function(shortUrl) {
jQuery("#idofaelement").attr("href", function() {
//process shortUrl
//return finalized url;
});
setTimeout(function() {
window.location = jQuery("#idofaelement").attr("href");
}, 0);
});
return false;
});
Thanks for all the help!