load website with hashs in the url

2019-07-25 13:02发布

I've got a webview that I save the url from anytime the application goes to the background/exits so I can preserve our users location on our website.

I store user-entered data in hashtags in the url:

https://test.org/?page=test#user_dat1=test#user_dat2=test

Where user_dat1 and user_dat2 is keeping track of where the user is and what they have entered on a page.

When I use the following:

NSURL *url = [NSURL URLWithString:@"https://test.org/?page=test#user_dat1=test#user_dat2=test"];
[self.mywebview loadRequest:[NSURLRequest requestWithURL:url]];

I get this out:

https://test.org/?page=test%23user_dat1=test%23user_dat2=test

Which crashes both my php and js.

How can I force hashtags to not be encoded?

EDIT: Code solution I made with guidance from marked solution

function read_hashes(){
    try { // I know I shouldn't use try... but this is a easy way to reject invalid hashes
        var hashes = window.location.hash;
        hashes = hashes.substring(1);
        hashes = JSON.parse(decodeURIComponent(hashes));
        if (hashes["user_dat1"] != null){//check if var is in json hash
            //do what you need to do with this var.
        }
        ...
    } catch(err){}

}
function put_hashes(){
    var hashes = {};
    hashes["user_dat1"] = "test data";
    hashes = encodeURIComponent(JSON.stringify(hashes));
    window.location.hash ="#" + hashes;
}

This allows me to store variables in a js hash to keep user data in a form. And just a note, I know this is a security issue, I don't use this on any page that this would result in a security issue.

标签: ios uiwebview
1条回答
趁早两清
2楼-- · 2019-07-25 14:05

not with NSURL -- this is an invalid url if it wasn't encoded.

NSURL *url = [NSURL URLWithString:@"https://test.org/?page=test#user_dat1=test#user_dat2=test"]; returns nil ==> showing you the string is not a valid url

to re-iterate: invalid urls are just not possible with NSURL Loading System.


what makes it invalid are the two hashes. Encode 1 then fix your decoding and send test.org/?page=test#user_dat1=test%23user_dat2=test


the op only wants the fragment inside his local JS it turned out. So Id suggest fixing the encoding locally

查看更多
登录 后发表回答