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 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧