window.location.href and **.replace concatenates the URL instead of replacing? - javascript

I've got an issue, using window.location.href or windown.location.replace() seems to concatenate my URL instead of replacing and redirecting.
Here's my code:
$("#languages p").click(function() {
$language = $(this).text();
$lang = $language.toLowerCase();
var url = 'www.becreativeagencja.com/elplast-wp/';
var position = url.indexOf('/') + 12;
window.location.replace([url.slice(0, position), $lang, url.slice(position)].join(''));
});
Live preview at: www.becreativeagencja.com/elplast-wp --- the PL/EN/DE/RU boxes in top-right corner
What am I doing wrong? Or is that wordpress that messes it up?

Related

Maintaining scroll position after hyperlink postback

I have tried numerious different approaches to my problem, but none of them seem to work out. I basically activate and deactivate users using a asp.net hyperlink and the problem is as soon as you do that, the page scrolls back up because of the postback it creates, so it will be annoying to scroll back down if you have a list of 1000 users. Here is the code iv'e been trying out without success!
// I use this variable for navigating the url for my hyperlink
var toggleUrl = "AdminListUsers.aspx?column=" + (IsClicked.FirstOrDefault().Key ?? "Name") + "&direc=" + (IsClicked.FirstOrDefault().Value) + "&a=chstat&q=" + id.ToString() + "&d=" + disabled + "&z=" + Server.UrlEncode(txtSearchFor.Text);
var hl = new HyperLink(); //These hyperlinks are the same
hl.Text = status;
hl.Style.Add(HtmlTextWriterStyle.Color, (disabled ? "red" : "green"));
hl.NavigateUrl = toggleUrl;
hl.Attributes.Add("onclick", "saveScroll(this);return true;");
cell.Controls.Add(hl);
tr.Cells.Add(cell);
cell = new TableCell();
cell.Width = new Unit("10%");
cell.Controls.Add(new LiteralControl("<nobr>"));
var linkbtn = new HyperLink //These hyperlinks are the same
{
//Here as you can see are my attributes for the hyperlink
NavigateUrl = toggleUrl,
Width = 16,
Height = 16,
CssClass = disabled ? "user-status-disabled" : "user-status-enabled"
};
linkbtn.Attributes.Add("id", "aButton_" + id);
ScriptManager.RegisterStartupScript(Page, typeof(Page), "ScrollToADiv", "setTimeout(scrollToDiv, 1);", true); // Not working
linkbtn.Attributes.Add("onclick", "window.scrollTo(0, location.hash);"); // Not working either
cell.Controls.Add(linkbtn);
cell.Controls.Add(new LiteralControl(" "));
As per my understanding, you could set the MaintainScrollPositionOnPostback to true in any of the below three ways.
Web.config Level => pages maintainScrollPositionOnPostBack="true" />
Page Level => <%# Page MaintainScrollPositionOnPostback="true" %>
Code Level => Page.MaintainScrollPositionOnPostBack = true;
Hope this Helps!!
EDIT
Code help for the comment below (assuming jQuery is being used):
$(".user-status-enabled").on("click", function() {
var $this = $(this);
var scrollPosition = $this.scrollTop();
$this.attr("href", $this.attr("href") + "&scrollPosition=" + scrollPosition);
});
And on the target screen, access this scrollPosition from Query String and set the scroll position on dom Ready

Difficulty constructing Absolute URL

www.baxter.com source page, shows most of the href links starting with the word baxter, like this -
href="/baxter/corporate.page?">About Baxter<
So the way I can construct an absolute url from the above is by combining the base url, www.baxter.com and the relative url /baxter/corporate.page?giving me www.baxter.com/baxter/corporate.page? which results in 404, cause the actual url is www.baxter.com/corporate.page?
I know how to generally parse relative URLs in PHP but is there a way to sense and remove words from relative urls like these?
Also mouseover on About Baxter on www.baxter.com web page displays the correct url, www.baxter.com/corporate.page? at bottom left of the page - where is this coming from? can it be accessed?
Will deeply appreciate any help/pointers...
EDIT on Nov 7:
In main.js, they are removing /baxter:
var fixer = function() {
var init = function() {
var digitasFinder = /(proto)|(cms-)|(teamsite-)/
, baxterFinder = /(\/baxter\/)/
, $allAnchors = $("a")
, $allForms = $("form");
digitasFinder.test(location.host) || ($allAnchors.each(function() {
var $this = $(this)
, actualHref = $this.attr("href");
if (baxterFinder.test(actualHref)) {
var newHref = actualHref.replace(baxterFinder, "/");
$this.attr("href", newHref)
}
}
),
$allForms.each(function() {
var $this = $(this)
, actualAction = $this.attr("action");
if (baxterFinder.test(actualAction)) {
var newAction = actualAction.replace(baxterFinder, "/");
$this.attr("action", newAction)
}
}
))
}
;
return {
init: init
}
}
Looks like some JavaScript executed on page load is modifying the hrefs of the links.
You could try duplicating the effects of the JS code (ie. remove '/baxter' from the links), or for a more generic solution, you could use a headless browser to execute the JS code and then evaluate the resulting DOM. Look into the Mink project for a PHP-based solution.

Reload Parent Window without POST

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.

Dynamically modify the url using javascript

I would like to change the url of the page when the user select another page to visit. The url is dynamically replace the original one.
eg.
If user visit page 1 , the url will be book.html?page=1
If page 30 then book.html?page=30 and so on.
However, when I change the link using javascript, it falls into a infinite loop.
It seems I keep visit->change link ->visit ->change link->.... How to fix this problem?
eg. When the link change, don't access the page.
var currURL = $(location).attr('href');
var index = currURL.indexOf('?');
currURL = currURL.substring(0, index != -1 ? index : currURL.length);
// fall into loop
$(location).attr('href', currURL + '?page=' + pageNo);
You can do this pretty easily with just standard javascript.
if(location.href.indexOf('?') !== -1 && location.href.indexof('?page=') === -1)
{
var urlArray = location.href.split('?');
var newURL = urlArray[0] + "?page=" + urlArray[1];
location.href = newURL;
}

Debugging the base URL element with Firebug

I'm adding the base URL tag to the document head using JS, so the relative links on the page work. But it does not take effect, and Firebug (debugging addon for Firefox) shows the <BASE /> element greyed out.. why? Does this mean Firefox cannot understand it or the syntax is incorrect?
Image http://www.freeimagehosting.net/uploads/a3122c1ddd.png
http://www.w3schools.com/TAGS/tag_base.asp
the base tag has two components href and target. Yours seems to be fine. coold you give some example of the links on which it is failing?
see http://ashita.org/StackOverflow/base_test.html for a demonstration. (my test)
Edit: see comments
function addBase(url) {
var regex = /^(https?|ftp):\/\//;
var a = Array.prototype.slice.call(document.getElementsByTagName('a'),0);
var link = Array.prototype.slice.call(document.getElementsByTagName('link'),0);
var script = Array.prototype.slice.call(document.getElementsByTagName('script'),0);
var img = Array.prototype.slice.call(document.getElementsByTagName('img'),0);
var hrefs = a.concat(link);
var srcs = img.concat(script);
var element,href,src;
for (var i=0,len=hrefs.length;i<len;++i) {
element = hrefs[i];
href = element.getAttribute("href");
if (href) {
if (!regex.test(href)) {
href = (url + "/" + href).replace("//","/"); //to handle double slash collision
element.setAttribute("href",href);
}
}
}
for (var i=0,len=srcs.length;i<len;++i) {
element = srcs[i];
src = element.getAttribute("src");
if (src) {
if (!regex.test(src)) {
src = (url + "/" + src).replace("//","/"); //to handle double slash collision
element.setAttribute("src",src);
}
}
}
}
Tested and working in firefox

Categories