JS window.location.href not showing same value as in address bar - javascript

I need to read the url using some JS code in order to extract some parameters and execute some tasks depending on them. However I have two problems:
-The webpage is not mine so I cannot modify anything on it or inspect it in great detail. I just write some script that the client load from its webpage, and executes some functions on load. I can modify this script but not anything else.
-In this functions, I save in a variable the window.location.href value, but when doing some logs in order to verify what is reading, I see that the value does not correspond to the actual url in the address bar. Moreover, if I check the value of window.location.href in the browser console, then the value matches with the address bar!
I check this value at the start of my script and at the end and it does not match in any case. I don't know at which point of the loading does my script start execution, and I don't know what is causing this behaviour.
EDIT: Here is some code, I won't show it all as most of it works fine and doesn't have relation to my problem.
This is what I sent to my client to put in its webpage:
var s1 = document.createElement('script');
s1.src = 'source_of_my_script;
document.head.appendChild(s1);
s1.onload = function () {
s();
};
This is part of my script:
function s(){
var my_url_var = window.location.href;
console.log("1st value", my_url_var);
var param = extractParamFromUrl(my_url_var); //this functions get some value written in the url
switch (param){
case 'value_0':
// do things
case 'value_1':
// do other things
defalut:
// do default actions
}
console.log("final value", window.location.href);
}
I cannot show you the exact URLs because of privacy reasons, but they are similar to these ones:
Address bar url (and what i get if I check window.location.href in browser console): https://www.client_dummy_url.com/dummy/cobranded?origin=8000097& ... (more params separated by &)
What I get from window.location.href in script: https://www.client_dummy_url.com/drfd01/main/control.do?action=start&internet=S&app=EP& ... (more params, but not all the ones I want!)
Many thanks!

After some tries, I managed to get it to work with the solution posted by #Vaibhav at Access parent URL from iframe
//var my_url_var = window.location.href;
var my_url_var = (window.location != window.parent.location)
? document.referrer
: document.location.href;

Related

Attempting window.location or window.location.href redirect which is causing a loop

I'm attempting to use javascript to determine if the user is using a certain language and if they're not using english then for the page to load a different page BUT with the params of which I've grabbed from the url.
I have been able to load the page with the params but I keep falling into a loop reloading the page, even after skimming through the countless other examples, such as: this or this.
function locateUserLanguage() {
var languageValue = (navigator.languages ? navigator.languages[0] : (navigator.language || navigator.userLanguage)).split('-');
var url = window.location.href.split('?');
var baseUrl = url[0];
var urlParams = url[1];
if (languageValue[0] === 'en') {
console.log('no redirect needed, stay here.');
} else {
// I tried to set location into a variable but also wasn't working.
// var newURL = window.location.href.replace(window.location.href, 'https://www.mysite.dog/?' + urlParams);
window.location.href = 'https://www.mysite.dog/?' + urlParams
}
} locateUserLanguage();
I've attempted to place a return true; as well as return false; but neither stop the loop.
I've tried window.location.replace(); and setting the window.location.href straight to what I need, but it's continuing to loop.
There is a possibility that the script in which this function is written is executed in both of your pages (english and non-english) on load. So, as soon as the page is loaded, locateUserLanguage function is executed in both english and non-english website causing the infinite loop.
You need to put a check before you call locateUserLanguage function.
Suppose english website has url = "www.myside.com" and non-english website has url "www.myside.aus". So the condition needs to be
if (window.location.host === "www.myside.com") { locateUserLanguage() }
This will make sure that locateUserLanguage is called only in english website.
Or other apporach can be to load this script only in english website which will avoid the usage of conditional statement.
Hope it helps. Revert for any doubts.

Browser does not replace an include file by its including file

I am an absolute beginner in JS.
1) What I'm trying to do:
My web pages are composed of an index.php which is the same for all the files of a directory and one of a set of content.inc, like this: index.php?open=content.inc. This is done by a PHP snippet in the index.php and works well.
However, Google indexes all the content.inc files. The user's browser then displays the content.inc without the framing index.php. This I want to avoid. I therefore add a modest script at the beginning of each content.inc (which I would convert into a function once it runs) to tell the browser that instead of displaying the content.inc, it should display index.php?open=content.inc.
2) My unworkable solution:
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
if (filename.indexOf("index.php") = -1)
{ var frame_name = "index.php?open="+filename;
window.location.replace(frame_name);
};
The browser (Firefox 60) ignores this; it displays content.inc. (I also have versions of this script which get the browser into an endless loop.)
What is wrong here? Please help!
PS: Please be assured that I have done extensive web search on this problem and found many pages of complaints about location.replace getting into an infinite loop; but none matches my situation. However, I gratefully accept a helpful link as an answer.
For starters, you have an error in this line:
if (filename.indexOf("index.php") = -1)
That's an assignment and will always evaluate to true, you need to use == or === (which should be more performant).
The guilty line is on your test case (see JP de la Torre answer). And to improve, here's a snippet to demo how to analyze the url with a regular expression :
function redirect(url) {
if(url && url.indexOf('.inc') >= 0) {
return url.replace(/\/(\w+)\.inc/, '/index.php?open=$1');
}
return url;
}
let urls = [
window.location.href,
'http://google.fr',
'http://example.com/index.php?open=wazaa',
'http://example.com/wazza.inc'
];
urls.forEach(url => {
console.log(url, ' => ', redirect(url));
});
The regexp will capture any text between a / and .inc. You can use it then as replacement value with the $1.
And applied to your case, you simply need :
if(window.location.href.indexOf('.inc') >= 0) {
window.location.href = window.location.href.replace(/\/(\w+)\.inc/, '/index.php?open=$1');
}
You can also use .htaccess server side to redirect request for .inc files on your index.php if mod_rewrite is enabled.
The solution to the problem of including an INC file called separately is the one proposed by Bertrand in his second code snippet above. It presupposes (correctly) that the inc extension is omitted in the replacement.
As I reported above, Firefox may get into an endless loop if it opens a PHP file directly, i.e. without involving the local host (with its php module).

JavaScript Page Not Redirecting Properly

I'm trying to create a page system for user_profile.html using a parameter from the URL and accessing using JavaScript.
However, for some reason my page does not refresh using the # parameter. I'm not sure why this is happening. I've put my redirection function and the output below.
Code:
function pageRedirect(page) {
var url = window.location.href.replace('#'+window.location.hash.substr(1), '#'+page);
console.log("####");
console.log(url);
console.log("####");
window.location.href = url;
}
Chrome console output:
####
user_profile.js:296 http://**********/user_profile.html#1
user_profile.js:297 ####
Navigated to http://**********/user_profile.html
Even though the URL gets changed to the same thing with a #1 at the end it does not get refreshed with that parameter.
The simplest way to change the hash of an url will be :
window.location.hash = page; // not the URL, just the '#something' part without the '#'
And if you need to reload the page after this, you can do this :
window.location.reload();

Is it possible for the admin to get the full sourcecode of my js-file if I redirect a Javascript file to a local modified Javascript file?

I created a google-chrome-extension which redirects all requests of a javascript-file on a website to a modified version of this file which is on my harddrive.
It works and I do it simplified like this:
... redirectUrl: chrome.extension.getURL("modified.js") ...
Modified.js is the same javascript file except that I modified a line in the code.
I changed something that looks like
var message = mytext.value;
to var message = aes.encrypt(mytext.value,"mysecretkey");
My question is now is it possible for the admin of this website where I redirect the javascript-file to modify his webpage that he can obtain "mysecretkey". (The admin knows how my extension works and which line is modified but doesn't know the used key)
Thanks in advance
Yes, the "admin" can read the source code of your code.
Your method is very insecure. There are two ways to read "mysecretkey".
Let's start with the non-trivial one: Get a reference to the source. Examples, assume that your aes.encrypt method looks like this:
(function() {
var aes = {encrypt: function(val, key) {
if (key.indexOf('whatever')) {/* ... */}
}};
})();
Then it can be compromised using:
(function(indexOf) {
String.prototype.indexOf = function(term) {
if (term !== 'known') (new Image).src = '/report.php?t=' + term;
return indexOf.apply(this, arguments);
};
})(String.prototype.indexOf);
Many prototype methods result in possible leaking, as well as arguments.callee. If the "admin" wants to break your code, he'll surely be able to achieve this.
The other method is much easier to implement:
var x = new XMLHttpRequest();
x.open('GET', '/possiblymodified.js');
x.onload = function() {
console.log(x.responseText); // Full source code here....
};
x.send();
You could replace the XMLHttpRequest method, but at this point, you're just playing the cat and mouse game. Whenever you think that you've secured your code, the other will find a way to break it (for instance, using the first described method).
Since the admin can control any aspect of the site, they could easily modify aes.encrypt to post the second argument to them and then continue as normal. Therefore your secret key would be immediately revealed.
No. The Web administrator would have no way of seeing what you set it to before it could get sent to the server where he could see it.

Redirecting to a page in a domain using greasemonkey

Basically i want to access site http://www.domain.com
what i want to do is that upon logging in, it should directly take me to
http://www.domain.com/access.aspx
But I have very little knowledge of java script, so far i made it but its continuely redirecting in in a loop like
http://www.domain.com/access.aspx/access.aspx/access.aspx/access.aspx/access.aspx/access.aspx
Why is it redirecting again and again, i just want it to redirect it once.
This is my existing code
var loc = window.location.href; var a = loc +"access.aspx"; window.open(a);
I am using a separate script for logging in, and separate for redirecting.
You don't seem to be checking if redirection is required so I suspect that your redirection logic is being applied even when you're already on the page you want to be on. Consider one of the following:
Add an exclude rule which will cause your script to be not be executed on the access.aspx page.
#exclude http://www.domain.com/access.aspx.
Check before you redirect, something like
var loc = window.location.href;
if(loc != 'http://www.domain.com/access.aspx'){
var a = loc +"access.aspx";
window.open(a);
}

Categories

Resources