rustwasm / wasm-bindgen

Facilitating high-level interactions between Wasm modules and JavaScript
https://rustwasm.github.io/docs/wasm-bindgen/
Apache License 2.0
7.86k stars 1.08k forks source link

web_sys: Missing stuff about URLSearchParams #2669

Open SpriteOvO opened 3 years ago

SpriteOvO commented 3 years ago

Motivation

I'm trying to edit a Url's parameters, which requires keeping some of the specified parameters and removing others beyond that. Since URLSearchParams does not seem to provide to_string() and iterative methods, this is difficult to accomplish.

Proposed Solution

Implement the missing things about URLSearchParams: URLSearchParams.toString() URLSearchParams.entries() Url::set_search_params - Setter for the searchParams field.

Alternatives

Maybe I have to write the parameter parser manually.

Additional Context

I am not sure if i'm missing something, or just they are not currently implemented because there are some technical troubles? I didn't find any relevant discussions. Thanks in advance! ❤️

Jules-Bertholet commented 3 years ago

UrlSearchParams implements Deref<Target = Object>; the methods you are looking for appear to be accessible via that

SpriteOvO commented 3 years ago

@Jules-Bertholet Thanks for the reply, I found the method entries there, but it doesn't work for UrlSearchParams.

Here is my code:

pub fn example() {
    let url = web_sys::Url::new("https://example.com/abc?p1=1&p2=2&p3=3").unwrap();
    let params: web_sys::UrlSearchParams = url.search_params();

    console::log(&format!("(expect true) has p1: {}", params.has("p1")));
    console::log(&format!("(expect true) has p2: {}", params.has("p2")));
    console::log(&format!("(expect true) has p3: {}", params.has("p3")));
    console::log(&format!("(expect false) has p4: {}", params.has("p4")));

    let entries = js_sys::Object::entries(&params);

    console::log(&format!("(expect 3) entries length: {}", entries.length()));

    entries.for_each(&mut |value, index, _| {
        console::log(&format!("[{}] value: {:?}", index, value));
    });
}

Output:

console.log div contained:
    (expect true) has p1: true
    (expect true) has p2: true
    (expect true) has p3: true
    (expect false) has p4: false
    (expect 3) entries length: 0

And I still didn't find the method Url::set_search_params anywhere.

jonboj commented 3 years ago

For Url::set_search_params. Maybe there is an other way to interpretate the web_sys api. For an Url a reference to its UrlSearchParams is obtained with https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.Url.html#method.search_params

On the obtained reference a parameter is set with https://rustwasm.github.io/wasm-bindgen/api/web_sys/struct.UrlSearchParams.html#method.set

Similar approach for e.g. append and delete of a parameter.