skip to Main Content

I have a rich text editor on the front page that creates rich text content, and now I get this content, just like:

<u style="font-size: 60px; font-family: &quot;Times New Roman&quot;;"><em><strong><span data-slate-string="true">abc</span></strong></em></u>

Now I want to take this into the url and jump to the second page,

const allQuery = encodeURIComponent(`isResult=true&content=${htmlString}`);
const jumpUrl = `${secondPageUrl}?${allQuery}`;
// then go to jumpUrl to open the second page

However, when I went to obtain and parse the url content on the second page, there was a problem.

new URL(decodeURIComponent(window.location.href)).searchParams.get('content');

I got

<u style="font-size: 60px; font-family: 

I found that the problem appeared in the place of font-family, the html content was cut off, and the html tag could not be completely closed, resulting in the failure to render the content correctly.
What should I do ?

2

Answers


  1. Encoding within encoding is causing the confusion. Take a look at the result here (a partial MCVE of the problem described):

    const htmlString = '<u style="font-size: 60px; font-family: &quot;Times New Roman&quot;;"><em><strong><span data-slate-string="true">abc</span></strong></em></u>';
    const allQuery = encodeURIComponent(`isResult=true&content=${htmlString}`);
    const jumpUrl = `http://www.test.com/?${allQuery}`;
    
    const newUrl = new URL(decodeURIComponent(jumpUrl));
    console.log(newUrl);

    The resulting URL contains & characters, which are going to confuse the structure of that URL entirely. & separates different query string values, so in your code you’re only reading the first query string value.

    It sounds like you want to encode htmlString before encoding the rest of the query string keys/values around it:

    const allQuery = encodeURIComponent(`isResult=true&content=${encodeURIComponent(htmlString)}`);
    

    Which you’d then be able to decode as a complete value later:

    const htmlString = '<u style="font-size: 60px; font-family: &quot;Times New Roman&quot;;"><em><strong><span data-slate-string="true">abc</span></strong></em></u>';
    const allQuery = encodeURIComponent(`isResult=true&content=${encodeURIComponent(htmlString)}`);
    const jumpUrl = `http://www.test.com/?${allQuery}`;
    
    const result = new URL(decodeURIComponent(jumpUrl)).searchParams.get('content');
    console.log(result);
    Login or Signup to reply.
  2. You should use encodeURIComponent on only the parameter value, and not use decodeURIComponent at all, because URL is decoding for you.

    const allQuery = `isResult=true&content=${encodeURIComponent(htmlString)}`;
    
    // or
    
    const allQuery = new URLSearchParams({
        isResult: 'true',
        content: htmlString,
    });
    
    new URL(window.location.href).searchParams.get('content')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search