how to remove /?fbclid=... in nuxt url - javascript

hello there i like to remove the facebook analytic forced url parameter /?fbclid= https://www.example.com/?fbclid=..., from my host url, when redirected from facebook by clicking the url, the problem is the nuxt-link-exact-active class is not applied if redirected with this parameter.
Thanks

For simple cases like https://www.example.com/?fbclid=... where fbclid is the first and only parameter, it can be done by a simple server configuration.
So for example put this in the .htaccess file:
RewriteEngine on
<if "%{QUERY_STRING} =~ /^fbclid=/">
RewriteRule . %{REQUEST_URI}? [R=301,L]
</if>
Note the ? after %{REQUEST_URI}. It deletes the query string completely.
In other cases (where fbclid was appended to other parameters) this example does nothing - more complicated code is needed for that.

In simple cases like https://www.example.com/?fbclid=... where fbclid is the only parameter, it should be a trivial Javascript like that:
<script>
// ideally this is on top of page; works on bottom as well
if(/^\?fbclid=/.test(location.search))
location.replace(location.href.replace(/\?fbclid.+/, ""));
</script>
This checks if ?fbclid=... is a URL search parameter and navigates to the same location with that part removed.
It may also be fine to remove any search parameter and not checking for fbclid.
<script>
if(location.search) location.replace(location.href.replace(/\?.+/, ""));
</script>

i could finally solved it with this:
methods: {
removeFacebookHook() {
var fbParam = 'fbclid';
// Check if param exists
if (location.search.indexOf(fbParam + '=') !== -1) {
var replace = '';
try {
var url = new URL(location);
url.searchParams.delete(fbParam);
replace = url.href;
// Check if locale exists
if (window.location.href.indexOf(this.locale) > -1) {
window.history.replaceState(null, null, "/" + this.locale);
};
} catch (ex) {
var regExp = new RegExp('[?&]' + fbParam + '=.*$');
replace = location.search.replace(regExp, '');
replace = location.pathname + replace + location.hash;
}
history.replaceState(null, '', replace);
}
}
}
with the help of this post modiyf urls
I keep the nuxt-i18n route locale working with href.indexOf !
Unfortunately the nuxt alwaysRedirect made me remove the switcher...

I solve the Facebook Query string in a very simple way using JavaScript...
inclue this script in your Layout page or MastrPage
//facebook Route Script for Query string
function faceBookQuery() {
addEventListener('fetch', event => {
let url = new URL(event.request.url)
if (url.searchParams.has('fbclid'))
url.searchParams.delete('fbclid')
event.respondWith(
fetch(url, event.request)
);
});
}
Injoy

Il there is a #section like inhttps://www.example.com/file?fbclid=...#section (pervers facebook...) then code proposed by j.j. gives https://www.example.com/file.
Better code is
if(/^\?fbclid=/.test(location.search))
location.replace(location.href.replace(location.search, ""));
N.B. Removing any search parameter and not checking for fbclid will prevents passing variables via the url...
Thanks to j.j. for showing the way.

Related

Appending UTM parameters to my current URL

I am grabbing the utm parameters from the URL on my index page, and storing them in local storage, then I am using the script below to grab the parameters from local storage and appending them to the end of the contact page's URL.
<script>
var parameters = localStorage.getItem("url");
const nextURL = window.location.href + parameters;
window.history.replaceState(nextURL);
</script>
Problem: This script works perfectly, except each time I refresh the contact page, it appends the parameters again. How can I fix this?
Use URL and URLSearchParams to parse and modify the URL for you. That way you don't have to do any work to produce a valid string:
function buildUrl(fromURL, fromQuery) {
const url = new URL(fromURL);
const query = new URLSearchParams(fromQuery);
for (const [key, value] of query) {
url.searchParams.set(key, value);
}
return url.toString()
}
function test(fromURL, fromQuery) {
const url = buildUrl(fromURL, fromQuery);
return `fromURL: ${fromURL}
fromQuery: ${fromQuery}
result: ${url}
---------------------`;
}
console.log(test("http://example.com", ""));
console.log(test("http://example.com", "foo=1"));
console.log(test("http://example.com", "foo=1&bar=2"));
console.log(test("http://example.com", "foo=1&bar=2&baz=3"));
console.log(test("http://example.com?hello=world", ""));
console.log(test("http://example.com?hello=world", "foo=1"));
console.log(test("http://example.com?hello=world", "foo=1&bar=2"));
console.log(test("http://example.com?hello=world", "foo=1&bar=2&baz=3"));
console.log(test("http://example.com?bar=someValue", ""));
console.log(test("http://example.com?bar=someValue", "foo=1"));
console.log(test("http://example.com?bar=someValue", "foo=1&bar=2"));
console.log(test("http://example.com?bar=someValue", "foo=1&bar=2&baz=3"));
You can always do a quick if statement to check if parameters exists in the current URL and if not, add it.
if(window.location.href.indexOf("?" + parameters) == -1){
const nextURL = window.location.href + '?' + parameters;
window.history.replaceState('', '', nextURL);
}

window.location causing continuous loop using

I'm attempting to append to the URL, a query string based on a particular condition. The problem I'm having is, the following code causes the page to loop continuously:
function taoExtendedIdleTime() {
if (trackingJson.loginType === 'explicit') {
var myURL = window.location;
window.location = myURL + "&debugMode=true&setIdleTime=60000";
}
}
taoExtendedIdleTime();
To correct this, I attempted the following, which checks if this query already exists. If not, add it:
function taoExtendedIdleTime() {
if (trackingJson.loginType === 'explicit') {
var myURL = window.location;
if (myURL.indexOf("&debugMode=true&setIdleTime=60000") == -1) {
window.location = myURL + "&debugMode=true&setIdleTime=60000";
}
}
}
taoExtendedIdleTime();
In my dev environment, this doesn't get executed at all. When I add it to Console, I get the following error: Uncaught TypeError: myURL.indexOf is not a function, and references the fourth line of this snippet: if(myURL.indexOf...).
Any help/guidance you can provide is most appreciated!!
because you are trying to get an object. window.location will return you Location object. what you are looking for is window.location.href which will return url of current location.
function taoExtendedIdleTime() {
if (trackingJson.loginType === 'explicit') {
var myURL = window.location.href;
window.location.href = myURL + "&debugMode=true&setIdleTime=60000";
} }
taoExtendedIdleTime();
Based on the documentation, window.location is a Location object (not a String), so it doesn't have an indexOf method. You might be interested in its search property though.
Or if you wanna go cleaner, URL.searchParams might help.

Set body class based on url with params

Im trying to set a body class based on the url - I can get it to work with a plain /Tablet/ url, like the code below.
But I need to set it to a url that has params in it, and I can't get that to work. How do I do it with this url?
/Tablets/?param=grid&pld0page=1&spcs=1
Script:
$(function() {
var loc = window.location.href; // returns the full URL
if(/Tablets/.test(loc)) {
$('body').addClass('test');
}
});
If, as you have mentioned in comments, the query parameter order is important, you can use this...
var url = location.pathname + location.search
console.info(url)
$(document.body).toggleClass('test',
url === '/Tablets/?param=grid&pld0page=1&spcs=1')
This lets you omit the URL scheme, host and port parts, focusing only on the path and query parameters.
You just have to search for text you want in the url string. You are doing fine in the code above. Just change
$(function() {
var loc = window.location.href; // returns the full URL
if(loc.includes('Tablets')) { // will return true/false
$('body').addClass('test');
}
});
Read on includes or here. You can do the same for other tests too, if you are checking for other strings in url. Hope this helps.
You can use this
$(function() {
var url = window.location.href;
url = url.replace(/^.*\/\/[^\/]+/, '')
if(url == '/Tablets?param=grid&pld0page=1&spcs=1') {
$('body').addClass('test');
}
});
If your URL is "http://www.google.com/?param=grid&pld0page=1&spcs=1", then the above queryString variable would be equal to "?param=grid&pld0page=1&spcs=1".
You can check the string is not empty
Replace your code with this
var loc = window.location.href; // returns the full URL
var url = loc.split( '/' );
var chunk = url[ url.length - 2 ];
if(loc.indexOf(chunk) >= 0) {
$('body').addClass('test');
}
var loc = 'http://localhost/Tablets/?param=grid&pld0page=1&spcs=35';
var patt = new RegExp("/Tablets/");
if(patt.test(loc) && loc.split('?').length > 1)
{
console.log('true');
$('body').addClass('test');
}
else
{
console.log('false');
$('body').removeClass('test');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Javascript remove all get variables with history push state

How can I remove all get variables with javascript history push state?
It should work in the following cases:
http://example.com/slug1/slug2/index.php?myvar=1&myvar2=4
http://example.com/index.php?myvar=1&myvar2=4
http://example.com/slug1/slug2/?myvar=1&myvar2=4
http://example.com/slug2/?myvar=1&myvar2=4
And after it should look like this:
http://example.com/slug1/slug2/index.php
http://example.com/index.php
http://example.com/slug1/slug2/
http://example.com/slug2/
Maybe like a function like this:
function removeGetVariablesFromUrl() {
// Do stuff
}
It should not return the address with the change, it should change the actual url in the address field without reload the page.
It was really simple:
function removeGetVariablesFromUrl(my_url) {
my_url = "An url without get variables";
history.pushState({}, 'The title', my_url);
}
Here is a dynamic way of doing this in javascript:
var url = window.location.href;
if(url.indexOf("?") != -1) {
var resUrl = url.split("?");
if(typeof window.history.pushState == 'function') {
window.history.pushState({}, "Hide", resUrl[0]);
}
}
This will take you current URL and remove anything after and including a '?' symbol (which indicates $_GET variables)

How to split url and call a javascript function

I want to convert my all wordpress theme link to be ajax enable. So, I am using this code
siteUrl = "http://" + top.location.host.toString(),
url = '';
$(document).delegate("a[href^='" + siteUrl + "']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/])", "click", function() {
var pathname = this.pathname;
return false;
});
Now, I want if this var pathname is like /ebook/some-ebook then I want to call the post_load() function and if it is like /ebook then I want to call the post_archive() javascript function.
ebook is a post-type and some-ebook is %postname%.
Thank you
I don't understand half of what you're asking...but it sounds like you just want to split() the pathname into its relevant pieces.
In that case, you can do something like the following:
var pathPieces = pathname.split('/', 3),
archiveName = pathPieces[1],
postName = pathPieces[2];
At that point, you can do whatever you want with those path pieces. For example:
if ( archiveName === 'ebook' ) {
post_archive();
}

Categories

Resources