Highlighting a word or sentence in iframe, using javascript/Jquery

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-24 21:19:14

问题


I am trying to change the background colour of word in iframe tag. I am able to search the word, but not getting how to change the colour. Here is my code.

$(document).ready(function () {
   $('#content').contents().find('head').append($("<style type='text/css'> .red{color:red;}</style>"));
   var cont = document.getElementById('content').contentWindow.document.body.innerHTML;
          
   if($("#content").contents().text().search("SEARCH WORD")!=-1){
     console.log("Found");
     //<span class="red"> SEARCH WORD </span>
   }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="padding-left: 0px;" class="col-sm-8 text-center">
  <iframe id="content" ng-src="http://locahost:8888/public/textfiles/sample.txt" 
          width="100%" height="500px" align="middle"></iframe>&emsp;
</div>

回答1:


As noted, CORS will not allow you to alter iFrames sourced from other domains you do not control without the proper CORS heading.

If you are on the same domain, you can possibly do something like find the word, alter it, and then replace the contents of the iframe with your new code. Here is a working fiddle and code For example:

<iframe src="http://fiddle.jshell.net/_display/" id="myIframe"></iframe>
<script>
var searchWord = "error";
$(document).ready(function(){
    $('#myIframe').ready(function(){
        var $html = $($('#myIframe').contents().find('body').html());
     if($html.contents().text().search(searchWord)!=-1){
       console.log("Found");
       var replaceWith = "<span style='color:red'>"+searchWord+"</span>"
       var newHTML = $html.text().replace(searchWord, replaceWith);
       $('#myIframe').contents().find('body').html(newHTML);
     }
   });
});
</script>



回答2:


Please don't forget the cross-domain policy, otherwise it won't work. And check this Search for word and highlight with jquery



来源:https://stackoverflow.com/questions/46851093/highlighting-a-word-or-sentence-in-iframe-using-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!