How to redirect url using javascript query - javascript

How do I redirect conditionally with query /xxx?xxx in the url link?
For example, anyone who come to my site with the below two link should be redirected to different pages.
mysite.com/contest?a => mysite.com/contest-a
mysite.com/contest?b => mysite.com/contest-b
Can this be done using both js and meta refresh?
How do I do this using .htaccess?

If there is a querystring, replace the first instance of ? with -
if (window.location.search.length)
window.location.href = window.location.href.replace('?','-');

Use
location.href
to detect url, where you are now. And
window.location.replace('mysite.com/contest-a ');
to do redirect.
But probably it is better to do it on server side, since it will be faster.

you can use the below script to do the re-direction.
window.onload = function()
{
var location = window.location;
if(location.indexOf("contest?a") > -1)
{
window.location.href = "mysite.com/contest-a";
}
else
{
window.location.href = "mysite.com/contest-b";
}
}

It's not possible to change the url without refreshing the page (except for hashes), and thus you would be better off not using that url in the first place to avoid unnecessary requests and hassle for the user. You could take a look at mod_rewrite which does that (transform a "nice url" from the user into an "ugly url" that your server actually understands)
In your example, a possible rule might be
RewriteRule ^mysite.com/contest-{.+} /mysite.com/contest?$1

If you're ok doing this kind of operation on the client side, you could embed the following snippet on your landing page (the page where the arriving user will be redirected), just after the <head> tag:
<script type="text/javascript">
var mapReferrer = function() {
var gotoURL;
switch(document.referrer) {
case "https://www.google.com": gotoURL = "http://<yoursite>/arrivedFromSearchEngine"; break;
case "https://www.facebook.es": gotoURL = "https://<yoursite>/engageFBusers"; break;
case "http://<yoursite>/contest?b": gotoURL = "http://<yoursite>/contest-b"; break;
};
if (gotoURL) window.location = gotoURL;
};
window.onload = mapReferrer;
</script>

Related

how to Restrict access to some urls of wordpress website from single referrer domain

hello my question is what is the best approach to Restrict access to some urls of wordpress website to single referrer domain.
as far as I am familar with javascript I found a way for that. but I think javascript code is not good, because the source code of the page does not change.
I wrote this code:
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
document.body.style.display="none";
var url = document.referrer;
var domainname;
var referal_code = getCookie("protect_faq_pages");
console.log(url);
if(url){
var anchor = document.createElement("a");
anchor.href = url;
domainname = anchor.host;
console.log(domainname);
if(domainname == "softwareservicetech.com"){
var cookieString = "protect_faq_pages=cWs#fgf$a1fD#FsC-)";
document.cookie = cookieString;
}
}else if(!(referal_code == "cWs#fgf$a1fD#FsC-)")){
document.getElementById("page").innerHTML="<p>Sorry you do not have permission to view the content</p>"
}
console.log(referal_code);
document.body.style.display="block";
this site can be accessed itself:
https://health-unity.com/
you can find out the page below is restriced on the view :
https://health-unity.com/help-centre/videos/
and also these pages too:
https://health-unity.com/help-centre/videos/video-number-2/
https://health-unity.com/help-centre/videos/video-number-1/
but when click on the link on below site (link to health-unity-videos):
https://softwareservicetech.com/testpage/
the archive page will be accessible after that. user can go to the pages below directly:
https://health-unity.com/help-centre/videos/video-number-2/
https://health-unity.com/help-centre/videos/video-number-1/
these were restricted before and now can be accessed by a cookie that is set.
but the problem is that page source still exist and did not changed by javascript code and user can view the page source. also I want that the cookie value should be hidden. because of these two problem I think javascript is not a good idea.
please share with me if there is way with javascript, php, or editing functions.php or .htaccess file to achieve this.
thank you for your response in advance
You can use $_SERVER['HTTP_REFERER'] in functions.php
For example:
<?php
add_action('init','check_referrer');
function check_referrer(){
if( str_contain($_SERVER['HTTP_REFERER'], 'https://example-domain.com/'){
// do somthing
}else{
// do somthing else
}
}
?>

Redirect in Javascript with multiple query params

I have this code :
if($('#category').val() == 4){
console.log("http://"+window.location.hostname+'/dailyGift?id_event='+$( "#sub-category" ).val()+'?week_id='+$('#week_id').val()+'?year_id='+$('#year_id').val());
window.location = "http://"+window.location.hostname+'/dailyGift?id_event='+$( "#sub-category" ).val()+'?week_id='+$('#week_id').val()+'?year_id='+$('#year_id').val();
}
In the console I have
http://myWebsite.dev/dailyGift?id_event=41?week_id=44?year_id=2016.
When I access directly works without problems, but jQuery does not make this redirect and I don't understand where is the problem.
You need to change all the ? with & except the first one
if($('#category').val() == 4){
console.log("http://"+window.location.hostname+'/dailyGift?id_event='+$( "#sub-category" ).val()+'&week_id='+$('#week_id').val()+'&year_id='+$('#year_id').val());
}
Please replace all "?" with "&", Correct URL would be :-
http://myWebsite.dev/dailyGift?id_event=41&week_id=44&year_id=2016
Also it would be good if you encrypt ids for security purpose.
You say that you want to redirect to a link but you're merely changing the location.href value which is equivalent to clicking a link.
Location.replace() will load the new resource in place of the current one. The current page will not be added to the session history so it will not be possible to return to it using the back button.
I've also cleaned up the use of " and ' in the url string to make it cleaner.
if ($('#category').val() == 4){
var url = "http://"+window.location.hostname+"/dailyGift?id_event="+$('#sub-category').val()+"&week_id="+$('#week_id').val()+"&year_id="+$('#year_id').val();
console.log(url);
window.location.replace(url);
}

I need change this meta refresh redirect structure to window.location method

I have a web-app in NodeJS that make certain redirects in sometimes using the method meta refresh. The problem is that this method are incompatible with Firefox (in Firefox not work meta refresh). And I need that the redirect goes well in all browsers and versions. I understand that the best way is use window.location method, is right?
The structure of the code that make the actual redirect is:
module.exports = (outcome) => {
return "(function(document) {"+
"var meta = document.createElement('meta');"+
"meta.setAttribute('http-equiv', 'refresh');"+
"meta.setAttribute('content', '0;URL=" + outcome + "');"+
"document.head.appendChild(meta);"+
"})(document);";
}
How would the final code with the window.location method?
Thank you very much!
You can use window.location.href.
A simple example would be:
window.location.href = 'http://example.com';
Or wrapped in your function:
module.exports = (outcome) => {
return "(function(document) {"+
"window.location.href='" + outcome + "';"+
"})(document);";
}

Forcing Javascript Redirection

I am trying to implement what seems to be very simple JavaScript redirection, via the following rudimentary command:
window.location.href = "http://www.somesite.com";
So far so good, it works. I also can do it via the following method:
location.replace("http://www.somesite.com");
No problem here, it works again! The problem comes when I loose the protocol out of the string:
window.location.href = "www.somesite.com";
OR:
location.replace("www.somesite.com");
It just appends the new location to the current url:
www.currentsite.com/www.somesite.com
Of cause, that's not what I want. Is there any way to force the redirect?
One way is to use protocol-relative url like this:
window.location = "//www.somesite.com";
Or
window.location = "//somesite.com";
This way, it would redirect and browser itself will take care of figuring out protocol part eg http or https
Working Example
The protocol is required.
How else would the browser know whether
location.replace("mysite.pl");
was going to a Polish website or a Perl script on the current website?
You could do something like this to add http:// to the URL if it's not already there... although I can't think of a reason for not just including it yourself. Why complicate things?
​function redirect(url) {
if(url.substr(4) != "http")
url = "http://" + url;
window.location.href = url;
}
redirect("www.google.com")
​

How to redirect to home page

How can I redirect a user to home page?
Example: mywebsite.example/ddfdf/fdfdsf and I want to redirect to mywebsite.example
However I want to do it without typing the static name. How can I do this?
document.location.href="/";
document.location.href="/";
or
window.location.href = "/";
According to the W3C, they are the same. In reality, for cross browser safety, you should use window.location rather than document.location.
See: http://www.w3.org/TR/Window/#window-location
(Note: I copied the difference explanation above, from this question.)
window.location.href = "/";
This worked for me.
If you have multiple folders/directories, you can use this:
window.location.href = "/folder_name/";
Can you do this on the server, using Apache's mod_rewrite for example? If not, you can use the window.location.replace method to erase the current URL from the back/forward history (to not break the back button) and go to the root of the web site:
window.location.replace('/');
maybe
var re = /^https?:\/\/[^/]+/i;
window.location.href = re.exec(window.location.href)[0];
is what you're looking for?
window.location = '/';
Should usually do the trick, but it depends on your sites directories. This will work for your example
strRetMsg ="<script>window.location.href = '../Other/Home.htm';</script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "Script", strRetMsg,false);
Put this code in Page Load.
var url = location.href;
var newurl = url.replace('some-domain.example','another-domain.example';);
location.href=newurl;
See this answer
https://stackoverflow.com/a/42291014/3901511
var url = location.href;
var newurl = url.replace('some-domain.example','another-domain.example';);
location.href=newurl;

Categories