I have passed props through to different components and pages before but this has been through link or just added these to the component tag itself.
The issue I have here is that the redirect is not going through a link tag or in a component tag and instead I am simply using window.locatio.href ="whatever the url is".
I simply want to pass a variable through to this (I am technically doing a refresh in this situation so window.location.reload() could also work if it is possible).
How would I pass through a variable within this.
When using express you can do fetch statements with an endpoint simialr to (might not be exact syntax) "./page${variableYouWant}" Then access sit in the express file using req.params.variableYouWant.
Is this possible to pass a variable this way and how would I then access it.
Here is the most important snippet of my code.
pageRelocator(mssg) {
if (mssg.length < 35) {
toast.info(`${mssg}`, {
draggable: true,
autoClose: 1500
});
window.location.href = "http://localhost:3000/completed-assessment";
} else if (mssg.length > 35) {
toast.error(`${mssg}`, {
draggable: true,
autoClose: 1500
});
//Here I would like to pass a variable
window.location.href = "http://localhost:3000/user-questions";
}
}
EDIT--
componentDidMount() {
const search = this.props.location.mssg;
alert(search); // returns the URL query String
const params = new URLSearchParams(search);
const IdFromURL = params.get("mssg");
this.setState({
questions: this.getItems(),
WorkStations: this.getWorkStations()
});
}
pageRelocator(mssg) {
if (mssg.length < 35) {
window.location.href = "http://localhost:3000/completed-assessment";
} else if (mssg.length > 35) {
window.location.href = `http://localhost:3000/user-questions?mssg=${mssg}`;
}
}
Try using the URLSearchParams which defines utility methods to work with the query string of URL.so to attach a variable you would do
var id=5;
window.location.href = `http://localhost:3000/user-questions?id=${id}`;
and to retreive id from the URL you would do
const search = props.location.search; // returns the URL query String
const params = new URLSearchParams(search);
const IdFromURL = params.get('id');
Hope this helps
If you want the data to be present even after refresh, try to pass the variable in params.
http://localhost:3000/completed-assessment?your_variable=value
If you want to use this params value you can use
window.location.search
Using URLSearchParams you can get the each params you've sent with the URL.
Please refer https://www.sitepoint.com/get-url-parameters-with-javascript/ for more info
Related
While being on a twitter account's page (let's say StackOverflow: https://twitter.com/stackoverflow), I'm trying to get the username of the account, then open a new window querying the account's username on google search. Finally I'd like to get the query text of the newly opened tab.
To do so, I did the following:
function getUserName(callback) {
url = window.location.href;
console.log(url);
sn = url.split("/").slice(-1)[0];
console.log(sn);
window.location.href = `https://google.com/search?q=${sn}`;
callback();
};
function getQuery() {
console.log(window.location.href);
}
getUserName(getQuery);
The problem is that it doesn't wait for the new page to be loaded and thus the console.log() form getQuery() is the twitter's one, instead of the google's.
I know this is a matter of callback and await/async, I've been reading a lot about it but those subjects are confusing me.
Just pass https://google.com/search?q=${sn} into a global variable and use that.
Like this:
let windowHref = window.location.href;
function getUserName(callback) {
url = window.location.href;
console.log(url);
sn = url.split("/").slice(-1)[0];
console.log(sn);
windowHref = `https://google.com/search?q=${sn}`;
window.location.href = windowHref;
callback();
};
function getQuery() {
console.log(windowHref);
}
getUserName(getQuery);
As far as getting the query text of the newly opened tab. You need make use of the callback function within your getUserName() function.
function getUserName(callback) {
url = window.location.href;
console.log(url);
sn = url.split("/").slice(-1)[0];
console.log(sn);
windowHref = `https://google.com/search?q=${sn}`;
callback(windowHref); // Sending back the url to the callback as parameter
};
function getQuery(queryText) { // Value returned from the callback.
console.log(queryText);
}
getUserName(getQuery);
I tried your scenario with linkedin: Sharing the snippets below:
I have a question, i wanted to know if there is a way to call a specific function if a specific page URL is opened?
#shop_modal is in http://myurl/liste-boutique.php
#dep_modal is in http://myurl/index.php
Right now, i have Error when i try to open the #dep_modal because JS cant find #shop_modal on that page same page, so it does not execute below that.
I think AJAX can help figuring this out, otherwise i will have to split the code in 2 JS files, which i don't want to
const new_shop = $("#new_shop")[0];
const save_shop = $("#shop_form")[0];
const close_shop_modal = $("#close_shop_modal")[0];
const new_departement = $("#new_dep")[0];
const save_departement = $("#dep_form")[0];
const close_dep_modal = $("#close_dep_modal")[0];
// I want this to be called if the URL is http://my-URL/liste-boutique.php
new_shop.addEventListener('click', function(){
$("#shop_modal")[0].style.visibility = "visible";
})
// I want this to be called if the URL is http://my-URL/index.php
new_departement.addEventListener('click', function(){
$("#dep_modal")[0].style.visibility = "visible";
})
i need to ask question, but i don't know what to change here
Thanks again !!
You can check window.location.href. E.g.
if (window.location.href === 'http://my-URL/liste-boutique.php') {
new_shop.addEventListener('click', function(){
$("#shop_modal")[0].style.visibility = "visible";
});
}
Instead of checking the url, check if the element you want to find is on the page:
var $new_shop = $("#new_shop");
if ($new_shop.length > 0) {
var new_shop = $new_shop[0];
new_shop.addEventListener('click', function(){
$("#shop_modal")[0].style.visibility = "visible";
})
}
(I've used $ prefix on $new_shop to show it's a jquery object just for clarity)
Or, using your code as-is:
var new_shop = $("#new_shop")[0];
if (new_shop != undefined) {
new_shop.addEventListener...
Alternatively, if you use jquery, you don't need to worry about it as it will automatically not apply if the element doesn't exist:
$("#new_shop").click(() => { $("#shop_modal)").fadeIn(); });
As i have created a method to call to edit page the code is shown below.
SelectStaff(_StaffEmit:any){
let StaffJson = JSON.stringify(_StaffEmit);
let _navigationExtras: NavigationExtras = {
queryParams: {
StaffJson
}
};
this._router.navigate(["StaffInfo"], _navigationExtras);
}
Now, this code redirects to StaffInfo.ts page which is successfully done. Here is the code where i receive my JSON data.
this._routeEdit.queryParams.subscribe(params => {
let StaffParsed = JSON.parse(params.StaffJson);
this.StaffModel.Id = StaffParsed.id;
this.StaffModel.FirstName = StaffParsed.firstName;
this.StaffModel.LastName = StaffParsed.lastName;
this.StaffModel.UserName = StaffParsed.username;
this.StaffModel.Email = StaffParsed.email;
this.StaffModel.Title = StaffParsed.title;
this.StaffModel.CellPhoneNo = StaffParsed.cellPhoneNo;
});
Now i have a problem as i call this JSON data it appends on the URL which i don't want to.
Here is the image below for it.
As i can see it uses GET verb but i don't want to show the data, any POST verb or NON-POST verb method to redirect with data would be appreciated.
The only way is to use skipLocationChange property could be used to protect a user from seeing URL change.
you could encode it in Base64, put in the query param and decode it again whenever you need
//encode to base64
btoa(JSON.stringify({username:"admin",firstname:"John",lastname:"Doe"}))
//eyJ1c2VybmFtZSI6ImFkbWluIiwiZmlyc3RuYW1lIjoiSm9obiIsImxhc3RuYW1lIjoiRG9lIn0
now put this string to the URL and whenever you need it just decode it
//decode to base64
JSON.parse(atob("eyJ1c2VybmFtZSI6ImFkbWluIiwiZmlyc3RuYW1lIjoiSm9obiIsImxhc3RuYW1lIjoiRG9lIn0"))
//"{"username":"admin","firstname":"John","lastname":"Doe"}"
Angular 7.2.0 and above. You can pass state in NavigationExtras object.
It can pass the state without reflecting state in url.
You can access data inside state that is pass by router in routed component and can be accessed inside constructor.
let StaffJson = JSON.stringify(_StaffEmit);
let _navigationExtras: NavigationExtras = {
state: {
StaffJson
}
};
this._router.navigate(["StaffInfo"], _navigationExtras);
}
XYZ Component to which router.navigate(['./XYZ`], _navigationExtras)
constructor(private router: Router) {
this.name = this.router.getCurrentNavigation().extras.state;
let StaffParsed = JSON.parse(params.StaffJson);
this.StaffModel.Id = StaffParsed.id;
this.StaffModel.FirstName = StaffParsed.firstName;
this.StaffModel.LastName = StaffParsed.lastName;
this.StaffModel.UserName = StaffParsed.username;
this.StaffModel.Email = StaffParsed.email;
this.StaffModel.Title = StaffParsed.title;
this.StaffModel.CellPhoneNo = StaffParsed.cellPhoneNo;
}
I would like to pass an object to a controllerA to another controllerB and display that object. To do it, I'm using ui-router with angularjs.
This is my controllerA which build the URL using $state.href():
const url = $state.href('home.stateA', {
objectA: objectA
});
window.open(url, '_blank');
Now, this my route file:
.state('home.stateA', {
url: '/stateA',
template: '<template-b></template-b>',
params: {
// object: null
objectA: null
}
})
And finnaly, I try to get my object in my controllerB like that:
// $scope.object = $stateParams.object;
$scope.object = $stateParams.objectA;
When I console.log $scope.object, I'm getting null which is the default value in my route file.
So what's going wrong ? I'm wondering if $window.open would not be the problem.
Thanks for helping me.
window.open(url, '_blank');
You are opening a new window and trying to pass an object.
Passing a String/Number
You can pass a string/number say id, as part of the URL, if your state URL is defined like '/stateUrl/:id'
and then you can access this using $stateParams.id
Sharing an object
You can use localStorage along with JSON.stringify and JSON.parse to share the object.
Set data
localStorage.setItem('object', JSON.stringify(object));
Get data
var object = JSON.parse(localStorage.getItem('object'));
I have just found the solution ->
ControllerA
const url = $state.href('stateA');
let newTab = $window.open(url);
newTab.objectA = objectA;
ControllerB:
$scope.objectA = $window.objectA
And the state is very simple :
.state('home.stateA', {
url: '/stateA',
template: '<template-b></template-b>',
})
I don't know if it's the best way to implement what I needed but at least it works. it may help someone else.
Thanks guys and have a nice day !
I suggest you use url parameter.
.state('home.stateA', {
url: '/stateA?object',
template: '<template-b></template-b>',
params: {
object: null
}
})
Do when open new tab page
const url = $state.href('home.stateA', {
objectA: JSON.stringify(objectA)
});
In controllerB
$scope.object = JSON.parse($stateParams.objectA);
Because when you are open new tab. The state param is lost
How can I remove "http://" from beginning of a URL inside view in an AngularJS app?
I have URLs in database like:
http://example.com/
http://example.com
example.com
but I only need to show
example.com
inside the view.
This deals with HTTP and HTTPS or any other URL. It uses the built-in URL class, which will handle all of the things you haven't thought of correctly.
app.filter('domain', function () {
return function (input) {
try {
var url = new URL(input);
return url.hostname;
} catch (DOMException) {
// Malformed URL. Return original (or something else).
return input; }
};
});
URLs that are correct and you might not have thought of:
http://example.com
http://example.com:8000
http://me#example.com
file://example.com
https://example.com
http://example.com/some-path
http://example.com?some-query-url
You may not need them now, but using the correct library function means your app won't break unexpectedly in future when someone tries to use it for something else.
use this filter in view
app.filter('domain', function () {
return function (input) {
var output = "",
matches;
var urls = /\w+:\/\/([\w|\.]+)/;
matches = urls.exec( input );
if (matches !== null) output = matches[1];
return output;
};
});