Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
818 views
in Technique[技术] by (71.8m points)

javascript - Next.js DOMPurify.sanitize() shows TypeError: dompurify__WEBPACK_IMPORTED_MODULE_6___default.a.sanitize is not a function

I am using DOMPurify.sanitize() inside dangerouslySetInnerHTML={{}} to display innerHtml returned from the database. For initial purpose I'm using getServersideProps() with next-redux-wrapper for this page.

I installed dompurify with: npm i -S dompurify, present version is: "^2.2.6".

My code:

    import DOMPurify from 'dompurify';
    import { useSelector } from 'react-redux';
    import { END } from 'redux-saga';
    import wrapper from '../redux/storeSetup';

    const EmployeePage = () => {
    
        const blog = useSelector(state => state.data);

        const html_body = blog[0].body_html;
    
        const clean = DOMPurify.sanitize(html_body);
    
        return(
           <div className="mainContainer">
                <div dangerouslySetInnerHTML ={{ __html: clean }} />
                <ul>
                    {blog.map((item) => (
                        <li key={item.author}>
                            <span>{item.author}</span><br/>
                            <span>{item.title}</span>
                            <h4>{item.body_delta}</h4>
                            <p>{item.body_html}</p>
                            <p>{item.created_on}</p>
                        </li>
                    ))}
                </ul>
            </div>
        );
    }

    export const getServerSideProps = wrapper.getServerSideProps( async ({store}) => {
        store.dispatch({type: GET_DATA});
        store.dispatch(END);
        await store.sagaTask.toPromise();    
    });
    export default EmployeePage;

But when I'm running this with npm run dev I'm getting this error: TypeError: dompurify__WEBPACK_IMPORTED_MODULE_1___default.a.sanitize is not a function.

What is wrong here? I tried with even simpler codes but everything shows the same error! What am I doing wrong?

question from:https://stackoverflow.com/questions/65646007/next-js-dompurify-sanitize-shows-typeerror-dompurify-webpack-imported-module

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

According to this: https://github.com/cure53/DOMPurify/issues/29#issuecomment-466626162

Try the follow (from the example above):

import { JSDOM } from 'jsdom'
import DOMPurify from 'dompurify'
const { window } = new JSDOM(html_body);
const domPurify = DOMPurify(window);
console.log(domPurify.sanitize(html_body));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...