Reputation: 3252
I'm able to get a param using the GetQueryParam
function from this answer in the WebLib.WebTools
unit to get parameters from the current URL.
One would assume the opposite of getting a param would be to set one using SetQueryParam
, but no! SetQueryParam
doesn't exist.
If I run the following code:
SetQueryParam('first_name', 'Shaun');
SetQueryParam('last_name', 'Roselt');
Then I get an error that says
identifier not found "SetQueryParam"
What is the function and unit to set a Query Parameter using Delphi code?
For some added info. Here is the current function I wrote that I'm using to update the URL params:
procedure SetQueryParam(key, value, url: String);
begin
asm
if (!url) url = window.location.href;
let re = new RegExp("([?&])" + key + "=.*?(&|#|$)(.*)", "gi"),hash;
if (re.test(url))
if (typeof value !== 'undefined' && value !== null)
url = url.replace(re, '$1' + key + "=" + value + '$2$3');
else {
hash = url.split('#');
url = hash[0].replace(re, '$1$3').replace(/(&|\?)$/, '');
if (typeof hash[1] !== 'undefined' && hash[1] !== null) url += '#' + hash[1];
}
else
if (typeof value !== 'undefined' && value !== null) {
const separator = url.indexOf('?') !== -1 ? '&' : '?';
hash = url.split('#');
url = hash[0] + separator + key + '=' + value;
if (typeof hash[1] !== 'undefined' && hash[1] !== null) url += '#' + hash[1];
}
window.history.pushState({ path: url }, '', url);
end;
end;
And then I can call the Delphi function as follows:
SetQueryParam('first_name', 'Shaun');
SetQueryParam('last_name', 'Roselt');
The above code works and it does what I need, but it's a mix between JavaScript and Delphi code. It's just messy and I don't like it.
Surely, there must be a built-in Delphi method for setting the URL param in TMS Web Core?
Upvotes: 1
Views: 396
Reputation: 28499
TMS Web Core has three global variables that you can use to access the commonly used functionality of the document
, window
and console
objects in JavaScript.
This is how they are declared as global variables in the Web
unit:
var
document: TJSDocument;
window: TJSWindow;
console: TJSConsole;
From the global window
variable, you can call pushState
the same way as you use it in your JavaScript code.
By accessing the window
object and using its function, you can rewrite your JavaScript code into native Delphi code.
Simple sample:
procedure TForm8.WebButton1Click(Sender: TObject);
var
NewUri: string;
begin
NewUri:= window.location.href + '?a=b'; // Needs more logic
window.history.pushState(nil, document.title, NewUri);
end;
As far as I am aware there is no built-in function in TMS Web Core to work with uris.
Upvotes: 1