I am trying to add search and page to my url for searching and pagination on a page.
const urlParams = new URLSearchParams(window.location.search);
if(!urlParams.has('search'){
urlParams.append('search', question);
}
if(!urlParams.has('page'){
urlParams.append('page', pageIndex);
}
This appears to do nothing to the actual url.
But when I call urlParams.toString()
then I can see that they have been added, but they are not in the actual url in the browser.
I'm using Chrome 107, so it should support it.
Am I missing something?
The documentation has not helped me so far.
Of course it does nothing with the actual URL, you are creating a URLParameters Object and updating it. what you are missing is:
window.loacation.search = urlParams.toString()
it will change the query string in the browser URL and reloads the page.
if you are not interested in reloading the page, you can use history DOM object
let url = new URL(window.location.href);
if(!(url.searchParams.has('search'))){
url.searchParams.append('search', question);
}
if(!(url.searchParams.has('page'))){
url.searchParams.append('page', pageIndex);
}
history.pushState({},'',url.href);
finally, if you want to update the page and search params anyway, you can use the url.searchParams.set() method, like:
url.searchParams.set('page', pageIndex);
it will append the parameter if it does not exist, and will update it if it does, without throwing exceptions.
You can try this way:
First, retrieve the current path. Then, append the urlParams to the retrieved path and use history.pushState() to set the new URL.
const question = "the question";
const pageIndex = 3;
const urlParams = new URLSearchParams(window.location.search);
if (! urlParams.has('search')) {
urlParams.append('search', question);
}
if (! urlParams.has('page')) {
urlParams.append('page', pageIndex);
}
const path = window.location.href.split('?')[0];
const newURL = `${path}?${urlParams}`;
history.pushState({}, '', newURL);
Sources:
MDN - URLSearchParams
MDN - History.pushState()
Get the URL without query string
Related
I need to append params to my query, but I always get different results. I tried a few ways but without success. Check code below.
First check my code which work without new URL (I need to use new URL).
let url = `${getBaseUrl()}/myUrl/search?surnames=${allData.join('%0A')}`
This works well, but when I use new URL:
let url = new URL('myUrl/search' , getBaseUrl())
url.searchParams.append('surnames' , allData);
The code above doesn't work, and I don't know the reason why?
I tried to inspect url and see different
Works: search?surnames=smith%0Ajordan
Doesn't work: search?surnames=smith%250Ajordan
The only difference is inside between "smith" and "jordan"
With %0A work
With %250A doesn't work
Not sure how this was generated.
The original % is being encoded as %25, so %0 becomes %250.
Try using an unencoded line feed (\n):
const
allData = ['smith', 'jordan'],
getBaseUrl = () => 'https://localhost:8080',
url = new URL('myUrl/search' , getBaseUrl());
url.searchParams.append('surnames', allData.join('\n'));
console.log(url); // https://localhost:8080/myUrl/search?surnames=smith%0Ajordan
Hi I have a case a URL simillar to this:
https://linkhere?response-content-disposition=inline; filename="placeholder.jpg"; filename*=UTF-8''placeholder.jpg response-content-type=image/jpeg&X-Amz-Algorithm=....sometextcontinueshere
I am trying to decode it like this and I need to take the filename
const decodedUrl = decodeURIComponent("linkhere")
const urlParams = new URLSearchParams(decodedUrl);
const filename = urlParams.get('filename');
console.log(decodedUrl)
But for some reason does not work the decoding properly, do you guys have any idea?
There is nothing built in that is magically going to get the filename since it is not a querystring paramter. The easiest thing you can do it change whatever is building this to have valid querystring parameters so you can parse it.
With what you have, you will need to read the one parameter that has the file name in it. After that you are going to have to parse out the filename from that string.
Basic idea:
var str = `https://linkhere?response-content-disposition=inline; filename="placeholder.jpg"; filename*=UTF-8''placeholder.jpg response-content-type=image/jpeg&X-Amz-Algorithm=....sometextcontinueshere`;
const url = new URL(str);
const parts = url.searchParams.get('response-content-disposition').split(/;\s/);
const fileNameParam = parts.find(x => x.startsWith('filename=')).match(/"([^"]+)"/)[1];
console.log(fileNameParam);
I am looking for a simple way (using JavaScript) to get part of the page URL to be added to the end of the iframe src URL.
Example, page URL: www.example.com/?id=XYZ
Then I need the XYZ part, which is the the ID to be added to the iframe src like so:
And iframe src: www.otheradress.com/XYZ
You can get the query string from your route with window.location.search (only what comes after the '?', included), and you can parse the parameters with the URLSearchParams like this const params = new URLSearchParams(window.location.search);.
After that, params is an object with specific methods, and you can obtain your param by name with params.get('id');.
So you only need to concatenate your base URL and this parameter and pass it to the src attribute of the iframe.
Complete example:
const baseIframeUrl = 'www.otheradress.com/';
const urlParams = new URLSearchParams(window.location.search);
document.getElementById('#yourIframe').src = baseIframeUrl . urlParams.get('id');
If you wanted to use the src attribute from the HTML, it would be:
const urlParams = new URLSearchParams(window.location.search);
document.getElementById('#yourIframe').src = document.getElementById('#yourIframe').src . urlParams.get('id');
Though be aware that this approach would fail when called multiple times unless you store somewhere the original URL.
Also, as pointed out by mplungjan, you cannot access the src of an iframe of another origin.
I would use URL and URLSearchParams
NOTE: You cannot READ the iFrame src from an iframe that has loaded a page from another origin for security reasons
const url = new URL("https://www.example.com/?id=XYZ"); // new URL(location.href);
const id = url.searchParams.get("id")
console.log(id)
const iFrameUrl = new URL("https://www.otheradress.com/")
iFrameUrl.pathname+=id;
console.log(iFrameUrl.toString()); // here you can set the source of the iFrame
I'm looking for a way to analyse each part of an url.
For example I have these URL:
gs://myproject.appspot.com/soundtracks/track-title.mp3
gs://myproject.appspot.com/videos/video-title.mpg
soundtracks/track-title.mp3
videos/video-title.mpg
https://www.youtube.com/watch?v=zra2DCd0DnY
https://youtu.be/QtSXxtVkR24
https://www.instagram.com/p/CFaxzamnNI
I need to identify:
the protocole: gs:// or none = internal, http(s):// = external
the domaine: ie, if it is www.youtube.com or youtu.be I will use the last match as the id
each component of the path: ie, if the media is in soundtracks i launch the audio tracks player and if it is in videos I launch the video player
I tested the simple Regex (JavaScript) :
/([a-zA-Z0-9_\-.%:\(\)~]+)/gi
It takes each set of characters usually used in urls, except separators / = ? as a match.
Result: https://regex101.com/r/eG0vW1/10
It is not bad. However I'm not experienced at all with this and I fear that there could be edge cases. Is it safe to use?
I suggest that you use JavaScript URL() constructor function supported by modern browsers (not IE):
const url = new URL('https://www.youtube.com/watch?v=zra2DCd0DnY');
const relative_url = new URL('/videos/video-title.mpg', 'https://example.net');
const protocol = url.protocol; // 'https:', with final :.
const domain = url.hostname;
const path = url.pathname;
const path_components = path.split('/');
const params = url.searchParams;
const youtube_id = params.get('v');
// Iterate all search params:
// (not necessarily supported by your browser)
for (const [key, value] of params) {
// do something with key and value.
}
// Or:
params.forEach(function(value, key){
// do something with key and value.
});
You will notice, that, for gc: url.pathname includes what could be expected in url.hostname, but, taking into account the nature of gc: links, this is a feature, not a bug.
Further reading: https://dmitripavlutin.com/parse-url-javascript/.
I want to count users that use my bookmark in my Piwik/Matomo instance.
This is my code:
x = new Image();
x.src = 'https://piwik.jcubic.pl/matomo.php?idsite=7&rec=1&action_name=bookmark&urlref=' + location.href;
The problem is that when I open the statistic for today I don't see website with bookmark or reference on which the script was executed. I did this in incognito mode, so there was not cookie that disabled tracking for my browser.
The bookmark is REPL for Scheme language, so it's more likely be website that have Scheme learning resource or YouTube with video about Scheme. I think it's not the problem that I will track the url when bookmark was executed, there will be no information about the actual user so I think this is fine.
You can try to encode your href
const searchParams = new URLSearchParams({idsite: 7, rec: 1, action_name: 'bookmark', urlref: location.href});
const url = new URL('https://piwik.jcubic.pl/matomo.php')
url.search = searchParams.toString()
x.src = url.href;
Then you will have a URL like this with encoded special chars:
"https://piwik.jcubic.pl/matomo.php?urlref=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F63977752%2Fhow-to-track-bookmarklet-usage-using-image-in-matomo"