Reputation: 3326
I've run into a situation (a little out of my control) whereby debug text is getting inserted into my DOM when the HTML is being rendered. The text looks like the following:
, NameSpace.ClassName, Version=x.x.x.x, Culture=neutral, PublicKeyToken=null
The text is just rendered inline, not in an element. If it were at least put inside a div
or a span
I could do something about it, but it's just part of the body
wherever a module is loaded. So first I tried the following:
var goodText = $('body').html();
goodText = goodText.replace(/, Plugin.[a-zA-Z0-9]*, Version=\d\.\d\.\d\.\d, Culture=neutral, PublicKeyToken=null/g, '');
$('body').html(goodText);
While this takes the text out of the mix, it's replacing the entire body
of the document and therefore jQuery's document ready is firing again. My other scripts start to cry like baby llamas in the Arctic and the page falls apart.
A typical chunk of the page looks like this, as output by a module:
<div class="row">
, NameSpace.ClassName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
<div> some stuff</div>
<script> $(function(){ // some script }); </script>
</div>
So, even if I target .row
, replace the text with the above regex/string.replace and set the HTML on the element, that jQuery block is getting executed again. Which plainly put is a big pile of hooky-doodle.
As a side, I am loading modules using RazorGenerator to build the DLLs and BoC's precompiled views in an Asp.Net MVC4 project.
I also tried using a class-level implementation of a custom ActionFilterAttribute but there is nothing in there I can trap/override where this text is actually being generated/rendered.
What are my options here? Can I scrub that text out in another way? Can I block the execution of that script block a second time? Do I have any other options in the ASP.NET request pipeline that would allow me to exercise that demon text?
Upvotes: 1
Views: 298
Reputation: 140220
$("body").contents().filter( function(){
return this.nodeType === 3 && /Version=\d\.\d\.\d\.\d/.test(this.nodeValue);
}).remove();
Edit: since it appears the text might not be directly under body, we need to walk through the entire dom:
function walk( root ) {
$( root ).contents().each( function() {
if( this.nodeType === 1 && this.nodeName.toLowerCase() !== "iframe" ) {
walk( this );
}
else if( this.nodeType === 3 && /Version=\d\.\d\.\d\.\d/.test(this.nodeValue)) {
$(this).remove();
}
});
}
walk( "body" );
Upvotes: 2
Reputation: 146014
Here's a working jsfiddle based on @Pointy's suggestion. Adjust your regex as needed for your specific details.
//This is from http://stackoverflow.com/a/4399718/266795
var getTextNodesIn = function(el) {
return $(el).find(":not(iframe)").andSelf().contents().filter(function() {
return this.nodeType == 3;
});
};
$(function () {
getTextNodesIn("body").each(function (index, node) {
if (/.*, NameSpace/.test(node.textContent)) {
$(node).remove();
}
});
});
Upvotes: 1