I have a URL redirection JS code on a number of pages i.e Mon.html, Tue.html etc, I want to combine it into one file and still redirect the user to the mobile version of the page depending on their screen width e.g
if (screen.width <= 800) {
window.location = "../m/days/mon.html";
}
This means that I have many JS files with a respective window.location
I'm trying to have one JS file with all the necessary redirects.
You can map current location to a redirect.
if(screen.width <= 800) {
switch(window.location) {
case firstLocation:
window.location = firstRedirect;
case secondLocation:
window.location = secondRedirect;
// other redirect cases
default:
throw new Error('no redirect assigned to current location');
}
}
Or if redirects has the same pattern you can modify current location according to that pattern. That would be more preferable, as it doesn't contain lots of hardcoded locations, so you don't have to update it manually every time.
if (screen.width <= 800) {
window.location = '../m/' + window.location;
}
Figured it out.
var screen_width = screen.width;
$(function() {
if ($('body').is('.index') && (screen_width <= 800)) {
window.location = "m/index.html";
}
});
Related
I want some helper function code to run based on whether the browser is in "desktop" mode, which is default, or "mobile" mode, which some specs require for mobile only functionality. Height is always 800, but width can be 600 or 1280.
login: function() {
var self = this;
var browserSize = browser.manage().window().getSize().then(function(size) {
// size is still an unresolved promise ;.;
return size;
});
// Go to login page
browser.get(browser.baseUrl); // Will redirect authed users to the application
// If not at the login page, logout first
if (browser.getCurrentUrl() !== browser.baseUrl) {
if (browserSize.width == 600) {
self.mobileLogout();
} else {
self.desktopLogout();
}
}
self.loginPage.login();
}
How do I either resolve the promise getSize returns or determine the browser width some other way?
You were so very close! This worked for me just now:
var browserSizeOfMe = browser.driver.manage().window().getSize().then(function(size) {
console.log(" BROWSER SIZE "+ JSON.stringify(size) );
return size;
});
You don't have to approach the problem of differentiating mobile and desktop judging by the size of the browser window. Instead, you can access the configured capabilities via getCapabilities(), please see examples at:
Protractor: accessing capabilities
you can get the browser width using this script
var width = window.innerWidth || document.body.clientWidth;
but i dont think this answers your problem
There was indeed too many promises going on in this function. I had to nest needing the width and the current url so things would be defined and usable at the correct times.
Roughly the working code:
login: function() {
var self = this;
browser.get(browser.baseUrl);
browser.getCurrentUrl().then(function(url) {
if(url !== browser.baseUrl) {
browser.manage().window().getSize().then(function(size) {
if (size.width == 600) {
self.mobileLogout();
} else {
self.desktopLogout();
}
}
}
self.loginPage.login();
}
}
It can be done using "viewport", have a look following link
http://www.w3schools.com/css/css_rwd_viewport.asp
I am trying to reload a parent window (same domain) with javascript from within an iframe.
window.parent.location.href = window.parent.location.href;
does not work here for some reason (no javascript errors).
I don't believe it is a problem with same origin policy, as the following works:
window.parent.location.reload();
The problem with this option is if the last request was a POST, it gets reloaded as POST.
Any ideas why the first option wouldn't work? Otherwise, is there another method that will reload the page without resubmitting any form data (e.g. perform a fresh GET request to the parent page URL)?
I have also tried:
top.frames.location.href = top.frames.location.href;
window.opener.location.href = window.opener.location.href
and various other iterations.
I tried this code:
window.location.href = window.location.href;
in an ordinary page (no frames) and it had no effect either. The browser must detect that it is the same URL being displayed and conclude that no action needs to be taken.
What you can do is add a dummy GET parameter and change it to force the browser to reload. The first load might look like this (with POST data included, not shown here of course):
http://www.example.com/page.html?a=1&b=2&dummy=32843493294348
Then to reload:
var dummy = Math.floor(Math.random() * 100000000000000);
window.parent.location.href = window.parent.location.href.replace(/dummy=[0-9]+/, "dummy=" + dummy);
Phari's answer worked for me, with a few adjustments to fit my use case:
var rdm = Math.floor(Math.random() * 100000000000000);
var url = window.parent.location.href;
if (url.indexOf("rdm") > 0) {
window.parent.location.href = url.replace(/rdm=[0-9]+/, "rdm=" + rdm);
} else {
var hsh = "";
if (url.indexOf("#") > 0) {
hash = "#" + url.split('#')[1];
url = url.split('#')[0];
}
if (url.indexOf("?") > 0) {
url = url + "&rdm=" + rdm + hsh;
} else {
url = url + "?rdm=" + rdm + hsh;
}
window.parent.location.href = url;
}
I'm sure this could be more efficient, but works ok.
I am new to Javascript. I am trying to navigate to a page and "scrape" the screen. I am using Firefox, Greasemonkey and Firebug. I amd trying to use location.href which might be the problem. I want to navigate to a page, parse the contents, use the contents to navigate to other pages. Here is an example (my site is different, but I am getting the same error/result):
location.href='http://www.w3schools.com/html/html_examples.asp';
/* parse and find text */
location.href='http://www.w3schools.com/html/tryit.asp?filename=tryhtml_intro';
alert('finished');
No matter what I do, Firebug/Greasemonkey just quits after the first location.href. The alert will show, but even if I have a breakpoint set there, it will run right past it. Any help is much appreciated.
Scenario 1: A lot of dynamically generated links (fetched with GM_xmlhttpRequest)
//...
//#include http://www.w3schools.com/html/html_examples.asp
//#grant GM_xmlhttpRequest
//...
var urls = [];
//parse text to generate some links on the fly and store them in urls[]
var i = 0, numUrls = urls.length, reportEntries = [], count = 0;
for(; i < numUrls; i++) {
GM_xmlhttpRequest({
method: 'GET',
url: urls[i],
onload: function(response) {
var returnedHtml = response.responseText;
//extract more information from returnedHtml and store it in reportEntries[i]
if(++count >= numUrls) {
//print reportEntries[] to form a report
alert('finished');
}
}
})
}
Note: If you need to save report as a text file to local disk, Greasemonkey is not a viable option as it does not have the privilege to open local files. None the less you can save it to online storage such as pastebin.com.
Scenario 2: Limited number of static links
//...
//#include http://some.landing/page
//#include http://www.w3schools.com/html/html_examples.asp
//#include http://www.w3schools.com/html/tryit.asp?filename=tryhtml_intro
//...
if('http://some.landing/page' == location.href) {
location.href = 'http://www.w3schools.com/html/html_examples.asp';
}
else if('http://www.w3schools.com/html/html_examples.asp' == location.href) {
/* parse and find text */
location.href='http://www.w3schools.com/html/tryit.asp?filename=tryhtml_intro';
}
else if('http://www.w3schools.com/html/tryit.asp?filename=tryhtml_intro' == location.href) {
alert('finished');
}
I'm trying to set up a website that loads pages through ajax calls replacing the current contents of with the ajax response. I'm putting a # and a page name at the end of my URLs so that people can book mark pages.
www.examplesite.com#home
www.examplesite.com#examples
www.examplesite.com#examples/example1
www.examplesite.com#examples/example2
I'm new to jQuery and to a lesser extent JavaScript but I'm trying to get a different page animation when I go to a page that is stored in a sub folder. fadeIn() works fine on both pages and pages in sub-folders however I can't get .slideDown() or .animate() to work at all. Here is an extract from my code:
<script>
//All pages are stored in a folder called 'pages' or a subfolder of 'pages'
$(document).ready(function(){
var myUrl = $(location).attr('href');
var noPage = myUrl.indexOf('#');
if(noPage == -1) {
location.hash = 'home';
}
window.onhashchange = function() {
pageChange();
}
function pageChange() {
var myUrl = $(location).attr('href');
var page = myUrl.substring(myUrl.indexOf('#') + 1, myUrl.length);
$.get('pages/' + page + '.html', function(pageHtml) {
if (page.indexOf('/') != -1) {
$('.main').hide().html(pageHtml).slideDown(400);
} else {
$('.main').hide().html(pageHtml).fadeIn(400);
}
});
};
pageChange();
});
</script>
If I'm approaching this from completely the wrong direction and that's why it's not working do feel free to point me in the correct direction by giving me an example of how it should work.
Got it!
I was using the css min-height property with a couple of my divs so that the page would expand automatically with the content if there was a lot on the page. If I remove the min-height property and replace it with a fixed height .slideDown() works fine.
Here are some links for more info if anyone else has the same issue:
http://www.only10types.com/2011/09/jquery-slidedown-doesnt-work-on.html
http://docs.jquery.com/Tutorials:Getting_Around_The_Minimum_Height_Glitch
I would take this...
if (page.indexOf('/') != -1) {
$('.main').hide().html(pageHtml).slideDown(400);
} else {
$('.main').hide().html(pageHtml).fadeIn(400);
}
And rearrange it to make sure your if statement is correct
if (page.indexOf('/') != -1) {
$('.main').hide().html(pageHtml).fadeIn(400);
} else {
$('.main').hide().html(pageHtml).slideDown(400);
}
If it now slides instead of fades, the if statement is corrupt
What about this ? Does this work ?
var main_div=$('.main');
main_div.hide();
$.get('pages/' + page + '.html', function(pageHtml) {
if (page.indexOf('/') != -1) {
main_div.html(pageHtml)
} else {
main_div.html(pageHtml)
}
});
main_div.slideDown(400);
maybe something in the CSS must be blocking it ? try disabling the CSS for the main class and try again ?
I am not looking for a simple redirect.
What I am trying to do is this.
Person A loads site BOB.com and clicks a link to page X.
Person B loads site TIM.com and clicks a link to the same page X.
Page X has a javascript command on it that says, If user came from site Bob.com then redirect to Bob.com/hello.
If user came from TIM.com then redirect to Tim.com/hello.
If user didnt come from ether then redirect to Frank.com/opps.
This page X is going to handle 404 errors for multiple domains so it will need to ONLY look at the domain name upto ".com". It should ignore everything past the ".com".
This is the script I started with.
<script type='text/javascript'>
var d = new String(window.location.host);
var p = new String(window.location.pathname);
var u = "http://" + d + p;
if ((u.indexOf("bob.com") == -1) && (u.indexOf("tim.com") == -1))
{
u = u.replace(location.host,"bob.com/hello");
window.location = u;
}
</script>
Use document.referrer
if(/http:\/\/(www\.)?bob\.com/.test(document.referrer)) {
window.location = "http://bob.com/hello";
}
else if(/http:\/\/(www\.)?tim\.com/.test(document.referrer)) {
window.location = "http://tim.com/hello";
}
else {
window.location = "http://frank.com/oops";
}
Instead of the regex, you can use indexOf like you did initially, but that would also match thisisthewrongbob.com and thisisthewrongtim.com; the regex is more robust.
document.referrer is the place to be
Use document.referrer to find where the user came from.
The updated code is
<script type='text/javascript'>
var ref = document.referrer,
host = ref.split('/')[2],
regexp = /(www\.)?(bob|tim).com$/,
match = host.match(regexp);
if(ref && !regexp.test(location.host)) {
/* Redirect only if the user landed on this page clicking on a link and
if the user is not visiting from bob.com/tim.com */
if (match) {
ref = ref.replace("http://" + match.shift() +"/hello");
} else {
ref = 'http://frank.com/oops';
}
window.location = ref;
}
</script>
working example (it displays a message rather than redirecting)