dongyouzhui1969 2017-08-06 09:09
浏览 1026

如何使用textarea插入html和javascript代码

I want to insert html and JavaScript code with textarea field in my database. Problem is code has inserted but its replaced all double question with backlash. How to insert this code with textarea.

<div id="TA_cdsratingsonlynarrow539" class="TA_cdsratingsonlynarrow"><ul id="Ny62NY" class="TA_links r04zlbt"><li id="jb9xdEapRG" class="sc9nmfeVX"><a target="_blank" href="https://www.tripadvisor.com/"><img src="https://www.tripadvisor.com/img/cdsi/img2/branding/tripadvisor_logo_transp_340x80-18034-2.png" alt="TripAdvisor"/></a></li></ul></div><script src="https://www.jscache.com/wejs?wtype=cdsratingsonlynarrow&amp;uniq=539&amp;locationId=671932&amp;lang=en_US&amp;border=false&amp;shadow=false&amp;display_version=2"></script>

  • 写回答

1条回答 默认 最新

  • dpl9717 2017-08-06 10:40
    关注

    It is possible to insert/inject html and javascript code using textarea input field into the current page.

    consider, you've following textarea:

    <div id="output"></div>
    <div style="margin: 25px auto; width: 80%; height: auto;">
        <form id="myform" name="myform">
            <textarea id="mytextarea" name="mytextarea" cols="90" rows="20"></textarea>
            <br> <button type="button" id="mybutton">execute</button>
        </form>
    </div>
    

    Now, you can add event listener to that above button to extract html and javascript code from the textarea and insert them to the page:

        window.addEventListener('load', function () {
            document.getElementById('mybutton').addEventListener('click', function (e) {
                var mytextarea = document.getElementById('mytextarea');
                var pattern = /<script>([^]+?)<\/script>/mg;
                var matches, txt = mytextarea.value;
                if (txt) {
                    while (matches = pattern.exec(txt)) {
                        if (matches[1]) {
                            var tContent = matches[1].replace(/(
    |)+/gm, '');
                            var s = document.createElement('script');
                            s.innerText = tContent;
                            document.body.appendChild(s);
                        }
                    }
                    txt = txt.replace(pattern, '');
                }
                if (txt) {
                    document.getElementById('output').innerHTML = txt;
                }
            });
        });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog