简体   繁体   中英

url containing “&” does not work with google pagespeed api

i am using Google pagespeed API to test urls of my site. it works fine as long as url structure doesn't contain any "&" (query string parameters) .

examples which (Works)

  1. http://www.example.com
  2. http://www.example.com/?id=1234

But when i change url something like this, then it doesn't show correct result

Example which Does not Works

1) http://www.example.com/?id=1234&sub=890

Api ignores the "&sub=890" part and returns the result for http://www.example.com/?id=1234

Looking at API Javascript Code:

 function runPagespeed() {        
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.async = true;
        var query = [
            'url=' + URL_TO_GET_RESULTS_FOR,
            'strategy=' + strategy,
            'callback=runPagespeedCallbacks',
            'key=' + API_KEY,
        ].join('&');
        s.src = API_URL + query;
        document.head.insertBefore(s, null);
    }

So looking at this function it shows that API will treat "sub=890" as its own parameter so it will ignore it.

When i use the url http://www.example.com/?id=1234&sub=890 on https://developers.google.com/speed/pagespeed/insights/ , it works fine and shows the Result

Note: I am using pagespeed sample code for testing which is https://developers.google.com/speed/docs/insights/v2/first-app

Any help would be highly appreciated

You need to encode the URI using encodeURIComponent so that the parameter is treated as input. Try the below

function runPagespeed() {        
        var s = document.createElement('script');
        s.type = 'text/javascript';
        s.async = true;
        var query = [
            'url=' + encodeURIComponent(URL_TO_GET_RESULTS_FOR),
            'strategy=' + strategy,
            'callback=runPagespeedCallbacks',
            'key=' + API_KEY,
        ].join('&');
        s.src = API_URL + query;
        document.head.insertBefore(s, null);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM