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;
So i am working on a Userscript and there is one major step i'm trying to find the easiest resolve with since i am very new to Javascript coding...I'm trying to perform/code a function that will open a specified URL:
EXAMPLE: Homepage ("http://www.EXAMPLE.com")
(page can be opened as 'Window.open' = Blank, or _self);
...when the parent or (current) URL that is open
EXAMPLE: innner.href = ("www.EXAMPLE.com/new/01262016/blah/blah/blah");
...has a text on the HTML documnt page that reads:
EXAMPLE TEXT from page ("www.EXAMPLE.com/new/01262016/blah/blah/blah");:
"this is the end of the page, please refresh to return back to homepage"
(TEXT: not the real keyword, but want to use phase as a detection for a setTimeout function to return back to home.)
Any help will be much appreicated, you guys are veryinformative here. Thanks in advance.
I think I have the gist of you question. It is a straighforward, though quite intensive, task to scan the entire text content of a page for specific keywords with JavaScript. However, if the keywords appear more than once (on multiple pages that should not redirect) then your users will get undesirable results.
A simple solution would be to add a class="last-page" attribute to the body-tag of the final page and run a function that checks for this. Something like....
HTML
<body class="last-page"><!--page content--></body>
JS
window.onload = function() {
var interval = 5000; // five seconds
if (document.body.classList.contains('last-page')) {
setTimeout(function() {
window.location.assign('http://the-next-page.com/');
}, interval);
}
};
Alternatively, if you have the ability to wrap the specified text in a uniquely identified html-tag, such as...
<span id="last-page">EXAMPLE TEXT</span>
...then the presence of this tag can be checked on each page load - similar to the function above:
window.onload = function() {
var interval = 5000;
if (document.getElementById('last-page') {
setTimeout(/* code as before */);
}
};
Yet another solution is to check the page URL against a variable...
window.onload = function() {
var finalURL = 'http://the-last-page.com/blah/...';
if (window.location === finalURL) {
/* same as before */
}
};
If this kind of thing is not an option please leave a comment and I'll add a function that gathers a pages entire text content and compares adjacent words to a pre-defined set of keys.
This question is related to a previous post: Check if user is using browser located in China or not
I am loading an external js library to evaluate which css do I want to load in my header. Following the accepted answer of the above mentionned post, I load the userinfo.io API in my HTML head, followed by the evaluation of the received data. Here is what I did:
<head>
...
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/userinfo/1.0.0/userinfo.min.js"></script>
<script type="text/javascript">
UserInfo.getInfo(function(data) {
// the "data" object contains the info
if (data.country.code == 'CN') {
// Load fallback fonts
document.write('<link href="http://fonts.useso.com/css?family=Source+Sans+Pro:200,400,700|Dancing+Script:400,700|PT+Serif|Open+Sans:400,300,700" rel="stylesheet" type="text/css">');
} else {
// Load google fonts
document.write('<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,400,700|Dancing+Script:400,700|PT+Serif|Open+Sans:400,300,700" rel="stylesheet" type="text/css">');
}
}, function(err) {
// the "err" object contains useful information in case of an error
});
</script>
</head>
Debugging the js in Firefox, I can see that the library is successfully being loaded. It first happened, that I got an error message "Reference Error: UserInfo not defined". I played a bit with the order of the lines in my html head (there are a few more css includes, some meta tags and the title of course). After putting the
<head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/userinfo/1.0.0/userinfo.min.js"></script>
...
<script type="text/javascript">
UserInfo.getInfo(function(data) {
// the "data" object contains the info
if (data.country.code == 'CN') {
// Load fallback fonts
document.write('<link href="http://fonts.useso.com/css?family=Source+Sans+Pro:200,400,700|Dancing+Script:400,700|PT+Serif|Open+Sans:400,300,700" rel="stylesheet" type="text/css">');
} else {
// Load google fonts
document.write('<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,400,700|Dancing+Script:400,700|PT+Serif|Open+Sans:400,300,700" rel="stylesheet" type="text/css">');
}
}, function(err) {
// the "err" object contains useful information in case of an error
});
</script>
</head>
as the first line inside the head tag, it started to actually recognize the object UserInfo and its method getInfo(). Meanwhile it also recognizes the function when I put the line back to it's original place (such as in the first code snippet). This behavior somehow made me wonder on how is javascript being executed in the head tag while loading the html page. Is it possible that once in a while the method is being called before the library is loaded?
Anyway, now when it successfully imports the userinfo.io library, the site does not load properly anymore. Having a look at the browser console I see:
Having a look at the source code of my page I only see the link tag that is properly loaded, but the rest of the page is missing.
So here's what I suppose:
I can somehow not use document.write() in the head tag because it interferes with the page loading. More likely I should access and modify the link tag by getElementById() after the page has successfully loaded. So I will actually trigger this with let's say jQuery's ready() function to be sure that the library has successfully loaded? I would appreciate any comment on these thoughts.
document.write() is a very dangerous function (to a web page). You should be more specific about where you want to write something (not the whole document!). So, in your HTML you might specify an empty div block, and assign it an id:
<div id="writehere"></div>
Then in your JavaScript you would do something like this:
var place; //global variable
and inside some page-initialization function do this:
place=document.getElementById("writehere");
and after that, you can do all the writing you want, wherever you want, such as:
place.innerHTML += "Special output text<br />";
You can even re-write it (use "=" instead of "+=" when you modify innerHTML).
I will confess that I may have missed one of the points you were asking about in your Question. I'm now getting the impression you want to specify extra stuff for the page to load during loading, and it isn't necessarily always going to be the same extra stuff. I'm not sure the head section is the correct place to try doing that, because I don't know about forcing the browser to pay attention to newly-added link items in the head section. I do know it can pay attention to SOME things, as in this example (which, while the code is called by an onload event associated with the body tag, puts an icon into the browser tab, or upper-left-corner of browser window):
var hd, itm;
hd = document.getElementById('ID_of_Head');
itm = document.createElement('link');
itm.id = 'whatever';
itm.rel = 'shortcut icon';
itm.type = 'image/png';
itm.href = 'desired URL'; //OOPS; my comment below wrongly says 'src' property
hd.appendChild(itm);
//you can now re-use the 'itm' variable to specify another link, if you wish
It is possible that the appendChild() function suffices to trigger the browser to pay attention to the newly-added link, in which case this might work generically, and not just for this specific example. On the other hand, I haven't tried adding multiple links; it is possible that only one of them at a time can be "paid attention to". In that case, though, there is still a way, involving a sequence of functions, each of which specifies adding just one link to the head. At the end of each function you would do this:
setTimeout('nextlinkfunc();', 200); //give each function a different name!
When the current link-adding function ends, it sets a timer and gives the browser a chance to pay attention to the just-added link. After 200 milliseconds (1/5 sec) the timer triggers the specified next function --where you would specify adding another link to the head. That function's last thing would be another setTimeOut() to a third function, with its own unique name.... A variation on that could be a more complicated single function, where a parameter is used to specify which "call" is being made to the function (the very first call to the function must specify a parameter value of 1, of course):
//Note need to declare the global 'hd' and 'itm' variables,
// and set the 'hd' variable, before calling this function the first time
function nextlinkfunc(p)
{ itm = document.createElement('link');
//more stuff as previously presented
switch(p++)
{ case 1: //Note each 'case' block could have extra 'conditional' code
itm.href = "URL_of_1st_link";
break;
case 2: //Conditional code can encompass many different combinations of URLs
itm.href = "URL_of_2nd_link";
break;
//etc
}
hd.appendChild(itm);
if(p<max_number_of_links_you_want_to_add)
setTimeout('nextlinkfunc('p');', 200);
}
Alright, this works fine! Thanks.
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/userinfo/1.0.0/userinfo.min.js"></script>
<script type="text/javascript">
UserInfo.getInfo(function(data) {
var elHead, elLink;
elLink = document.createElement('link');
elLink.rel = 'stylesheet';
elLink.type = 'text/css';
if (data.country.code == 'CN') {
elLink.href = 'http://fonts.useso.com/css?family=Source+Sans+Pro:200,400,700|Dancing+Script:400,700|PT+Serif|Open+Sans:400,300,700';
}else{
elLink.href = 'http://fonts.google.com/css?family=Source+Sans+Pro:200,400,700|Dancing+Script:400,700|PT+Serif|Open+Sans:400,300,700';
}
elHead = document.getElementsByTagName("head")[0];
elHead.appendChild(elLink);
}, function(err) {
});
</script>
...
<body onload="UserInfo.getInfo();">
I need to cache some <script src> that I receive via AJAX. Currently each call try to load the src via AJAX, as default. But the problem is that this script never change in a session and I need only re-eval this on document.
To be more clear, take this example of AJAX content result:
<strong>Hello World!</strong>
<script src="hello-world.js"></script>
If I call this AJAX three times, the hello-world.js is called three times too, but I need only re-execute this, without try to download it again. Browser cache help a lot, but I really do not can download it again every time.
I like to set some data to script, to jQuery know that I want only re-execute it, instead of download again. Like:
<script src="hello-world.js" data-cache="true"></script>
Any solution?
If think about a good solution for my case... I just replaced the src with data-src, so jQuery will not get the content automatically, so I have time to work with my content and find data-src and create my own cache system. Works fine to me.
You can check my code here:
// Cache system (outside of AJAX engine)
var script_cache = {};
// Inside of [jQuery.ajax].success method
// where "data_html" is my jQuery(data_html) AJAX response.
// Find all script with data-src
jQuery('script[data-src]', data_html).each(function() {
var self = jQuery(this),
self_src = self.data('src');
// If data was loaded before, so just execute it again
if(typeof script_cache[self_src] !== "undefined") {
jQuery.globalEval(script_cache[self_src]);
}
// Else, will load, cache and execute now
// Note that we download with dataType text
else {
jQuery.ajax(self_src, {
dataType: "text"
}).success(function(data) {
script_cache[self_src] = data;
jQuery.globalEval(data);
});
}
// Finally we remove the node, only to avoid problem
self.remove();
});
Alternative solutions are welcome.
when I start my index.php it calls my javascript file that has this code below:
when the application starts immediately this error appears:
and this can only happen on the internet explorers, there is no 'txtName' on index.php, because the. js is called for every page, there any way to improve this function ? tath i dont need to put manually the js in each page?
Anyone know how can I solve this ? Thank you very much...
Update:
After the updated question - you can test for the element first
function focus(){
var txtNameObj = document.getElementById('txtName');
if(txtNameObj){
txtNameObj.focus();
}
}
This should avoid the error with it not being defined.
Original
I can only guess there is one of two problems:
a.) Your DOM hasn't loaded yet (so even though that ID will exist, it doesn't yet)
b.) You do not have an element with that ID.
If the element does exist, be sure to only call the focus function once you are sure that the element is loaded. e.g. you could place it as a script tag just before the body close.
<script>
focus();
</script>
</body>
</html>
Why dont you put a conditional for this method:
In this case:
var iId = document.getElementById('txtName');
if(iId != null)
{
// Processing
}