I am using a JS popup window for an Oauth2 Implicit Grant. I'm using JS to monitor for URL changes to get the code grant.
newWindow.addEventListener('unload', function(e)
{
console.log(e.currentTarget.location);
if (e.currentTarget.location.href.includes('code='))
{
var url = new URL(e.currentTarget.location.href);
alert(url.searchParams.get('code'));
}
});
The problem I am having is that the location field is giving two different values for the href parameter.
As you can see in the image, the href parameter has two different values. How do I make sure I always get the second value?
The Location is evaluated some time before.
If you hover over the little blue i icon, it says:
Value below was evaluated just now.
Related
I currently have a requirement that after entering a keyword ~ the keyword will be placed at the end of a set of URLs as a parameter, and the set will redirect to the specified page to appear. But what I hope to achieve is that even if I jump to another page, the keyword I just entered will not disappear, and it will still stay in the input input box! The following is my current writing method, but it failed~ It seems that the last jump should be changed The parameters behind the URL are extracted and placed in the input box. But I am a novice in programming and I don’t know how to rewrite it to achieve it. I hope I can get your help, thank you
$("#js-search").on('click',function(){
let keyword = $("#keyword").val()
// Here, the entered keywords will be placed after the URL to jump to the specified page
window.location.href = `/help_center?keyword=${keyword}`;
$("#keyword").val(keyword)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="keyword">
<button id="js-search">send</button>
As I understand your question, Once you have redirected the user to another page, You are actually sending them to a different page you will no longer have access to the current page's DOM.
If your question is How to read the passed query param in redirected page? then you use the following code:
// ?keyword=hello
const params = (new URL(document.location)).searchParams;
const keyword = params.get("keyword"); //hello
If you actually updating the current page with the query parameter, Then you can follow the below code:
$("#js-search").on('click',function(){
const keyword = $("#keyword").val();
window.location.href = `?keyword=${keyword}`; // Updating the query param
});
// Setting updated query param
const params = (new URL(document.location)).searchParams;
$("#keyword").val(params.get("keyword"));
Title says it all, I would like to trigger a jQuery event that opens a unique model window depending on which URL is used. I've looked at a few solutions and all of them seem to require bootstrap which I am not using or simply don't seem to work for me.
I think i understand the logic, I'm just not sure how to actually code it and would be grateful for some help. Here is my thinking:
[STEP 1]
On page load, check the URL.
If the the url is normal e.g. "www.domain.com/example", don't do anything.
If the url has a substring on the end e.g. "www.domain.com/example/#red", "www.domain.com/example/#green", or "www.domain.com/example/#blue" etc., set that substring to a variable. In this case the variable would equal either red, green, or blue.
[STEP 2]
Insert the variable where the line of code says [color] and execute.
$("document").ready(function() {
$(".details, #[color]details").trigger('click');
});
use with window.location.hash. its will get the hash value form url with# .so no need to add # in the dom
$("document").ready(function() {
if(window.location.hash.trim().match(/(\w+)/)){
$(".details,"+window.location.hash+"details").trigger('click');
}
});
You can use document.referrer to get the Page URL.
Store it in a variable to fetch the last segment or the URL using substr().
Then check it in conditional operator if the last part is your desired text, add it to your class and trigger.
I ll paste my code which I used on the next page to trigger tab change for some requirement. I hope this will work for you too, hopefully. Thank you.
$(document).ready(function () {
var referrer = document.referrer; // Get the Url of the previous page
var lastPathSegment = referrer.substr(referrer.lastIndexOf('/') + 1); // extracts the last part e.g. the page name
if(lastPathSegment == "invoices.php"){
customer_detail_content();
$('a[href="#tab_6_2"]').trigger('click');
}
I want to extract out the query string values from the URL.
So, in the most upvoted answer in How can I get query string values in JavaScript? - window.location.search is used.
Is there any problem in using window.location.href?
I am trying to root cause a problem where in sometimes I am getting empty query string value when using location.href
The 2 properties return different things:
href: Is a DOMString containing the whole URL.
and:
search: Is a DOMString containing a '?' followed by the parameters of
the URL. Also known as "querystring"
So you could use one or the other, just make sure to account for the differences between the returned values in your function. If you decide to use the href property you will need to first extract the query string part (the part after the ?) before splitting it into pieces.
Browsers now have a URLSearchParams class that can help to parse search params. It has been around in modern browsers for almost 4 years now: https://caniuse.com/?search=URLSearchParams
let queryParams = new URLSearchParams(window.location.search)
queryParams.set('page', '1')
queryParams.toString()
queryParams.get('page')
queryParams.delete('page')
i use
var qr={};
window.location.search.substring(1).split("&").forEach(p => { qr[p.split("=")[0]] = p.split("=")[1] })
//use
console.log(qr["sample"]);
//or
console.log(qr.sample);
Note - if there is not location.href.search value you will get a null string.
You can explore the DOM of a page - any page - using a browser's Inspect feature to look at values.
You can learn a lot about the DOM using this procedure - more than most every even hear about.
Open the inspector (how depends on the browser but try right clicking anywhere on the page and check the drop down menu that you'll see - it may read Inspect or Inspect Object.
Once the inspector is open, click on console in the menu at the top of the inspector frame.
For Foxfire, the input line, where you can type in things to explore the DOM is at the bottom of the inspector window and is prefixed with >>
Note - Chrome shows you a multi-line input field, Firefox only a one line field. If you have Chrome - use it to inspect things, after you type something and press Enter the value you want will be displayed under what you type and the cursor moved down to the next blank line so you can enter something else.
Firefox allows you to view things but it clunky and a tad harder to use.
Into the input line or field, type:
document.location.
A list of all the properties for the location of the document (the URL) will be displayed and it has auto fill in to help you.
For example:
document.location.search will show any text in the URL following the # sign in the URL
document.location.href will show the you the entire URL
document.location.host will show you the host part of the URL
Experiment and look at all the properties listed for document.location and you'll learn quite about bit about the document.location. property.
You can also type window. and see a list of the window object's property - one of which will be document.
Instead of typing document.location.href you could make it harder to type by typing window.document.location.href
They produce the same results because the top property is always assumed to be window.
For Firefox - After you type something and hit enter, the results will be displayed above the input line. To bring up what you last typed, so you can change it, press the up arrow key wile the cursor is in the input line.
With Chrome - as I said above, when you press enter, the value will be displayed the line you just typed and the cursor will be moved down to the next blank line where you can enter the name of another property to see what it's value is.
Explore top. and self. - you'll find the are the top window object (if there are multi-frames on the page - frames, not iframes) and the current window.
Spending some time exploring the properties of window. self. top. will teach you a lot about the DOM (Document Object Model) that you might not ever come across.
If you don't seen an input field or line, make sure you click Console in the inspector top menu.
If you decided to use, say, document.location.href you will code it like that in your JavaScript to get the value or to set the value - you can change the href and have the browser go to another web page.
Note - one of the other answers said
"If you decide to use the href property you will need to first extract the query string part (the part after the ?) before splitting it into pieces"
You need not split anything off. Explore all of the properties of document.location and you'll see that you can get the hash, search, etc. already "split off" from the location string.
Hash is the value after a pound sign (#) in the URL
Search is the value after a question mark (?) in the URL
Here are some other things to look at:
document.links
document.links[0]
document.URL
document.body
Just browse through the DOM - you will learn a lot.
Am assuming you know javascript array and few method
Use the window.location.href
var url = 'site.com/seach?a=val0&b=val1'
split the '?'
var someArray = url.split('?');
The someArray looks like this ['site.com/seach', 'a=1000&b=c']
index 0 is the window.location and index 1 is queryString
var queryString = someArray[1];
Go futher a split '&' so u get a key=value
var keyValue = queryString.split('&');
keyVal looks like this ['a=val0', 'b=val1'];
Now lets get keys and values.
var keyArray=[], valArray=[];
Loop through the keyValue array and split '=' the update keyArray and valArray
for(var i = 0; i < keyValue.length; i++){
key = keyValue[i].split('=')[0];
val = keyValue[i].split('=')[1];
keyArray.push(key);
valArray.push(val);
}
Finally we have
keyArray = ['a', 'b'];
valArray = ['val0', 'val1'];
Our full codes looks like this.
var url = 'site.com/seach?a=val0&b=val1';
var someArray = url.split('?');
var queryString = someArray[1];
var keyValue = queryString.split('&');
var keyArray=[], valArray=[];
for(var i = 0; i < keyValue.length; i++){
key = keyValue[i].split('=')[0];
val = keyValue[i].split('=')[1];
keyArray.push(key);
valArray.push(val);
}
DONE!
I am experiencing odd behaviour in Chrome (v43.0.2357.134) whereby I am reading an anchor element's .href attribute, but in specific circumstances its value is an empty string.
I would like the .href value to be populated on all anchors.
Issue
Specifically, this is what is being observed:
//Bad (unwanted) behaviour
var currentElem = ; //Code to pick out an anchor element
console.info(currentElem.href); //"" (empty string)
console.info(currentElem.getAttribute('href'); //"path/to/other/page.html"
Edited to add/clarify: Note that in this screenshot, at the point of reaching the fourth line of code the value of nextPageUri is an empty string (otherwise would not have reached the debugger; line). The fifth line then populates nextPageUri with the .getAttribute('href') value, hence the value showing next to line two.
This is what is (correctly) seen within Firefox, and on the first TWO DOMs via Chrome:
//Good (desired) behaviour
var currentElem = ; //Code to pick out an anchor element
console.info(currentElem.href); //"http://example.org/root/dir/path/to/other/page.html"
console.info(currentElem.getAttribute('href'); //"path/to/other/page.html"
Background
Context: This is within a script to inline multiple pages of search results to a single page, and the anchor elements are located within a DOM retrieved via xmlHttpRequest. The code runs perfectly via Firefox for >100 pages.
Confusingly, the incorrect behaviour described above only occurs on the third and subsequent requests in the Chrome browser.
This is an issue with Chromium/Blink-based browsers: if you use DOMParser to parse string into a document, href properties with relative URI (i.e. doesn't start with http[s]) will be parsed as empty string.
To quote tkent from Chromium issue 291791:
That's because a document created by DOMParser doesn't have baseURI. Without baseURI, relative URI references are assumed as invalid.
Same thing happens if you use createHTMLDocument. (Chromium issue 568886)
Also, based on this test code posted by scarfacedeb on Github, src properties also exhibit the same behavior with relative URIs.
As you have pointed out, using getAttribute() instead of the dot notation works fine.
Chrome's "element.href" doesn't act any differently on the 3rd try than it does on the first 2 -- you mentioned that you are paginating, when this error happens. how does the "href" attribute on the Next Page link get set each time you arrive at the page? It seems likely that your code to evaluate the element's href attribute is simply running before the href is set -- as evidenced by your debugger being able to evaluate it after a pause.
Try and reproduce this issue in a plunkr.
I know you're checking if nextPageUri is empty.
But, could you try always using
nextPageUri = currentElem.getAttribute('href');
and see if that works?
I experienced a similar problem using a DOMParser for translating text/html pages coming from ajax requests and, after that, finding href's of <a> elements inside it.
For instructions purpose, this is how I'm using the parser
var parser = new DOMParser();
$.ajax({....}).done(function(request){
var page = parser.parseFromString(request, 'text/html');
});
Test yourself
If you want to test the behaviour of .href and .getAttribute("href") yourself, please run this code at chrome dev tools console:
parser = new DOMParser(); // create your DOMParser
// the next line creates a "document" element with an <a> tag inside it
parsed_page = parser.parseFromString('click here', 'text/html');
link = parsed_page.getElementsByTagName('a')[0]; // locate your <a> tag
link.href; // this line returns ""
link.getAttribute('href'); // this line returns "test"
I have a userscript (http://userscripts.org/scripts/show/179402) that I'm writing that adds a bar to Google Sites like the one they removed. I'm needing the script to take the value of the search field and add it to a url (Replacement URL) and have it replace the url (Original URL) on the bar. In other words, I need to update it where the search term carries over to other pages, like the original google bar they removed.
I've tried this a few different ways. One way I tried was getting the value this way. Which, gets the value fine.
$('#gbqfq').keyup(function() {
var searchterm = this.value;
});
Then I've tried to add the search term to a url that replaces the original URL this way
var url1search = "https://www.google.com/search?q="+searchterm;
$('#url1').attr("href", url1search);
How do you replace a url with a new url plus a variable?
I'm very new to JavaScript, I'm making this script to try to learn it. If someone can help me figure out how to do this I would appreciate it very much.
Ah sorry, I see your problem. searchterm is only defined inside the anonymous function, it would be undefined elsewhere. Try moving rest of the script inside that function too.