Check browser and language - javascript

I have a code (listed below) that checks if your browser language is set to "de". If your browser is "de" it will send you to the adress "de.html". If it's not "de" you will be sent to "en.html". This works fine but here is the problem:
This is for a Webflow website and they have a editor witch is url/?edit. The code still try to check your language when going to that adress. It just prints out url/?editenenenenenenenenen.. and so on. Is there a way to check if the user is on url/?edit and if so, do nothing?
var lang = window.navigator.language;
var userLang = window.navigator.userLanguage;
if (lang == "de" || userLang == "de") {
window.location.href = window.location.href + "de.html";
}
else {
window.location.href = window.location.href + "en.html";
}

Wrap another if statement around your current if like this:
if (!window.location.href.includes('/?edit')) { ... }
This will check if the user is on url/?edit and if so, does nothing.
As a whole:
var lang = window.navigator.language;
var userLang = window.navigator.userLanguage;
if (!window.location.href.includes('/?edit')) {
if (lang == "de" || userLang == "de") {
window.location.href = window.location.href + "de.html";
} else {
window.location.href = window.location.href + "en.html";
}
}

If the URL is www.somedomain.com/editor?edit, then you can get the ?edit part using :
window.location.search // '?edit'
Using that :
if(window.location.search === '?edit') return;
or more loosely :
if(window.location.search.includes('?edit')) return;

Related

Javascript add multiple if - window.location.hostname

I have 5 websites using the same DB, and I need to add an global .js to check window.location.hostname and redirect if dont match one of my domains:
if (window.location.hostname != 'mysite1.com')
if (window.location.hostname != 'mysite2.com')
if (window.location.hostname != 'mysite3.com')
if (window.location.hostname != 'mysite4.com')
if (window.location.hostname != 'mysite5.com')
{
window.location.href = 'https://google.com';
}
The js will be inserted in the DB, and will display in all my sites.
HOW to add multiple instances of IF...window.location.hostname ... in the RIGHT WAY
I don't know if I understood your question. If you want to merge those 'if' conditions you can do like this:
if(!['mysite1.com','mysite2.com','mysite3.com','mysite4.com','mysite5.com'].includes(window.location.hostname)){
window.location.href = 'https://google.com';
}
Change your code and add AND as follows:
if (window.location.hostname != 'mysite1.com'
&& window.location.hostname != 'mysite2.com'
&& window.location.hostname != 'mysite3.com'
&& window.location.hostname != 'mysite4.com'
&& window.location.hostname != 'mysite5.com')
{
window.location.href = 'https://google.com';
}
I would define a list (array) of all domains first and then check if the current domain is on the list
listOfHostnames = ['mysite1.com', 'mysite2.com', 'mysite3.com'];
if (!~window.location.hostname.indexOf(listOfHostnames)) {
window.location.href = 'https://google.com';
}

change Language without leaving current page - JavaScript

I have a website with a language selector. It works great, except that whenever I do change language, it always redirects back to the root page as opposed to staying on whichever current page the user is on.
How can I go about fixing this?
Here is my code:
function checkLanguage() {
let lang = localStorage.getItem('lang');
let urlLang = window.location.pathname.split('/')[1];
if(isNullOrWhitespace(urlLang)) {
if (!lang) {
lang = navigator.language.toLocaleLowerCase();
}
if (lang) {
let userLang = languageDictionary[lang];
changeLanguage(userLang);
}
}
else {
localStorage.setItem('lang', urlLang);
}
var windowWidth = $(window).width();
if (windowWidth < 500 && lang === 'th-th') {
$('.integrations-container').css('display', 'none');
};
};
function isNullOrWhitespace( input ) {
return !input || !input.trim();
}
checkLanguage();
// Changing language
function changeLanguage(lang) {
if (languageOptions.indexOf(lang) === -1) {
return;
}
localStorage.setItem('lang', lang);
window.location.href = '/' + lang;
}
languageOptions = ['en', 'zh-cn', 'zh-hk', 'jp-jp', 'ko-kr', 'th-th'];
languageDictionary = {
'en': 'en',
'en-gb': 'en',
'en-us': 'en',
'zh-cn': 'zh-cn',
'zh-hk': 'zh-ch',
'ko-kr': 'ko-kr',
'th-th': 'th-th',
'jp-jp': 'jp-jp',
}
Thank you kindle in advance! Also I am very new, so laymens terms is always appreciated :)
window.location.href = '/' + lang;
I think this line is always redirecting back to top page when language is changed.
It would be helpful if you can provide the example url of the page.
Try change it to below to redirect to current page when language is changed. I think it should work in top page too.
// Changing language
function changeLanguage(lang) {
if (languageOptions.indexOf(lang) === -1) {
return;
}
localStorage.setItem('lang', lang);
var urlData = window.location.pathname.split('/'); // /en/detail/test.html -> ["", "en", "detail", "test.html"]
urlData.splice(0, 2).join('/'); //cut out ["", "en"]
var newPath = urlData.join('/'); // detail/test.html
window.location.href = '/' + lang + '/'+ newPath; // /jp-jp/detail/test.html
}

Javascript detect language and redirect

I know there are many answers here. I have tried the following codes, but it keep not workings or keep redirect with showing a blank page.
I just want to detect all using Chinese language to go to the page with chinese, others go to English page.
How should I sueccessful do this function in a simple way?
Should i placed the detect code in both chi and eng page? and if the url included the "utm", how to keep this url with url after redirect?
http://www.testing.com/tc/testing.html?utm_source=test
<script type="text/javascript">
var userLang = navigator.language || navigator.userLanguage;
switch(userLang){
case 'zh-CN':
window.location.href = '/tc/testing.html;
break;
case 'zh-TW':
window.location.href = '/tc/testing.html';
break;
case 'zh-HK':
window.location.href = '/tc/testing.html';
break;
default:
// if it's something else fall back to the default
window.location.href = '/tc/testing.html';
break;
}
</script>
Or
<script type='text/javascript'>
var language = window.navigator.language;
if(language == 'zh-CN' || language == 'zh-TW' || language == 'zh-HK')
{
window.location.href = '../tc/testing.html'
}
else {
window.location.href = '../en/testing.html'
}
</script>

If statement does nothing javascript

Okay so here's a simple question that I understood but got asked... let's say you have an if statement
if (window.location.href == 'http://' ||
window.location.href == 'http://?pg=pgOldMainMenu' ||
window.location.href == 'http://default.asp#')
else {}
How can you say "if positive do nothing, else load this HTML"?
Simply like this
var href = window.location.href;
if (href == 'http://' ||
href == 'http://?pg=pgOldMainMenu' ||
href == 'http://default.asp#') {} // do nothing
else {
href = 'url you want to load';
}

Excute jquery if url is home page

I need to fire piece of jQuery code only if it is home page.
URL probability are
http://www.example.com
http://www.example.com/
http://www.example.com/default.aspx
How can i run code if it is any of the above url i can use
var currenturl = window.location
but then i have to change this every time i move my code to server as on local host my url is like
http://localhost:90/virtualDir/default.aspx
in asp.net we can get the it using various
HttpContext.Current.Request.Url.AbsolutePath
or
HttpContext.Current.Request.ApplicationPath
I am not sure what are the equivalent in jQuery
reference of asp.net example
UPDATE:
I have taken a simple approach as i could not find other easy way of doing it
var _href = $(location).attr('href').toLowerCase()
var _option1 = 'http://localhost:51407/virtualDir/Default.aspx';
var _option2 = 'http://www.example.com/Default.aspx';
var _option3 = 'http://www.example.com/';
if (_href == _option1.toLowerCase() || _href == _option2.toLowerCase() || _href == _option3.toLowerCase()) {
$(".bar-height").css("min-height", "689px");
// alert('aa');
}
else
{ //alert('bb'); }
Could you only include the script on the page where it's needed? i.e. only use <script type="text/javascript" src="homepage.js"></script> from default.aspx ?
If not, then, as dfsq said - use window.location.pathname .
var page = window.location.pathname;
if(page == '/' || page == '/default.aspx'){
// -- do stuff
}
You could just get the part after the last slash, to account for folder differences...
var page = window.location.toString();
page = page.substring(page.lastIndexOf('/'));
... but this would be true for both example.com/default.aspx and example.com/folder1/default.aspx.
Remember, this Javascript is client-side, so there's no equivalent to the C# example you linked.
You could use my approch to know exactly the page (also with urlrouting) to use it in javascript:
I use the body id to identify the page.
javascript code:
$(document).ready(function () {
if (document.body.id.indexOf('defaultPage') == 0) {
/*do something*/
}
});
Asp.net code:
in masterpage or page (aspx):
...
<body id="<%=BodyId %>">
...
code behind:
private string _bodyId;
public string BodyId
{
get
{
if (string.IsNullOrWhiteSpace(_bodyId))
{
var path = GetRealPagePath().TrimStart('/','~');
int index = path.LastIndexOf('.');
if (index > -1)
{
path = path.Substring(0, index);
}
_bodyId = path.Replace("/", "_").ToLower();
}
return string.Concat(_bodyId,"Page");
}
}
public string GetRealPagePath()
{
string rtn = Request.Path;
if (Page.RouteData != null && Page.RouteData.RouteHandler!= null)
{
try
{
if (Page.RouteData.RouteHandler.GetType() == typeof(PageRouteHandler))
{
rtn=((PageRouteHandler)Page.RouteData.RouteHandler).VirtualPath;
}
else
{
rtn = Page.Request.AppRelativeCurrentExecutionFilePath;
}
}
catch (Exception ex)
{
Logger.Error(string.Format("GetRealPagePath() Request.Path:{0} Page.Request.AppRelativeCurrentExecutionFilePath:{1}", Request.Path, rtn), ex);
}
}
return rtn;
}

Categories

Resources