Replace / Ignore JavaScript in a String - javascript

I wrote a small RSS reader with JQuery. At first theres a screen with the titles of the articles, when clicked on a title I load the content of that article. The problem is, it contains some google ads script, which will replace the content of the article and fill the whole screen with an advertisement.
The following script is what I am tying to replace or ignore:
<script type="text/javascript"><!--
google_ad_client = "ca-pub-8356817984200457";
/* ijsselmondenieuws.nl */
google_ad_slot = "9061178822";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
So I wrote a method which is supposed to remove the script by a simple replace:
var replaceScript='<script type="text/javascript"><!--\n' +
'google_ad_client = "ca-pub-8356817984200457";\n' +
'/* ijsselmondenieuws.nl */\n' +
'google_ad_slot = "9061178822";\n' +
'google_ad_width = 468;\n' +
'google_ad_height = 60;\n' +
'//-->\n' +
'</script>\n' +
'<script type="text/javascript"\n' +
'src="http://pagead2.googlesyndication.com/pagead/show_ads.js">\n' +
'</script>';
function removeADS(ads) {
removeAD = ads.replace(replaceScript, " ");
}
But this doesn't work, I think it's not flexible either (if it would work). When something changes in the script, the application will get stuck at the advertisement again. Is there some way to completely ignore this script while fetching the content from an RSS feed or a more flexible replacement script?
Any help is appreciated,
Thanks!

It's not very wise to parse xml/html with regex.
Use a dom parser (jquery is a beautiful one ...hint hint):
var rssContentString = '<rss version='2.0'>...',
xmlDoc = $.parseXml(rssContentString),
$xml = $(xmlDoc),
helper = $('<div />'),
result;
result = helper
.append(
$xml
.find('script')
.remove()
.end()
)
.text();
UPDATE
Based on the new comments, since you get your rss content like this :
content:$.trim($(v).find("content").text())
you can modify this expression to the following :
content:$.trim($(v).find("content").find('script').remove().end().text())

Related

write script without CDATA and Merge two scripts with same functions

I have these scripts which are almost the same but I'm unable to merge them into one..
also I want remove "CDATA" and keep the script functioning in blogger XML template
<script type='text/javascript'>// <![CDATA[
!function(){const e=document.querySelectorAll(".vplayer");for(var t=0;t<e.length;t++){console.log(e[t].dataset.v);const a="//i.ytimg.com/vi_webp/"+e[t].dataset.v+"/hqdefault.webp";var n=new Image;n.src=a,n.addEventListener("load",void e[t].appendChild(n)),e[t].addEventListener("click",function(){const e=document.createElement("iframe");e.setAttribute("allowfullscreen",""),e.setAttribute("frameborder","0"),e.setAttribute("src","//www.youtube.com/embed/"+this.dataset.v+"?rel=0&showinfo=0&autoplay=1&iv_load_policy=3&modestbranding=1&noCookie=false&origin=https%3A%2F%2Fwww.xotaku.com&widgetid=1"),this.innerHTML="",this.appendChild(e)})}}();// ]]></script>
and that the second
<script type='text/javascript'>// <![CDATA[
!function(){const e=document.querySelectorAll(".vplayerold");for(var t=0;t<e.length;t++){console.log(e[t].dataset.v);const a="//i.ytimg.com/vi/"+e[t].dataset.v+"/hqdefault.jpg";var n=new Image;n.src=a,n.addEventListener("load",void e[t].appendChild(n)),e[t].addEventListener("click",function(){const e=document.createElement("iframe");e.setAttribute("allowfullscreen",""),e.setAttribute("frameborder","0"),e.setAttribute("src","//www.youtube.com/embed/"+this.dataset.v+"?rel=0&showinfo=0&autoplay=1&iv_load_policy=3&modestbranding=1&noCookie=false&origin=https%3A%2F%2Fwww.xotaku.com&widgetid=1"),this.innerHTML="",this.appendChild(e)})}}();// ]]></script>
the scripts are the same and I dont want write the whole of it twice
I want this
const e = document.querySelectorAll(".vplayer");
to work with that
const a = "//i.ytimg.com/vi_webp/" + e[t].dataset.v + "/hqdefault.webp";
and this
const e = document.querySelectorAll(".vplayerold");
to work with that
const a="//i.ytimg.com/vi/"+e[t].dataset.v+"/hqdefault.jpg";
the rest of scripte work with both as well
I want remove "CDATA" and keep the script functioning in blogger XML template
That's not possible. It's pretty much required for valid XML unless you want to use escape sequences for <>'".
the scripts are the same and I dont want write the whole of it twice
Make that IEFE a named function declaration, give it parameters, call it twice with different arguments.
<script type="text/javascript">//<![CDATA[
function createPlayer(selector, makeUrl) {
const e = document.querySelectorAll(selector);
for (var t = 0; t < e.length; t++) {
console.log(e[t].dataset.v);
const a = makeUrl(e[t].dataset.v);
var n = new Image;
n.src = a;
n.addEventListener("load", void e[t].appendChild(n));
e[t].addEventListener("click", function() {
const e = document.createElement("iframe");
e.setAttribute("allowfullscreen", "");
e.setAttribute("frameborder", "0");
e.setAttribute("src", "//www.youtube.com/embed/" + this.dataset.v + "?rel=0&showinfo=0&autoplay=1&iv_load_policy=3&modestbranding=1&noCookie=false&origin=https%3A%2F%2Fwww.xotaku.com&widgetid=1");
this.innerHTML = "";
this.appendChild(e);
})
}
}
createPlayer(".vplayer", v => "//i.ytimg.com/vi_webp/" + v + "/hqdefault.webp");
createPlayer(".vplayerold", v => "//i.ytimg.com/vi/" + v + "/hqdefault.jpg");
//]]></script>
Merged example
You mean like this?
<script type='text/javascript'>// <![CDATA[
!function(){const e=document.querySelectorAll(".vplayer");for(var t=0;t<e.length;t++){console.log(e[t].dataset.v);const a="//i.ytimg.com/vi_webp/"+e[t].dataset.v+"/hqdefault.webp";var n=new Image;n.src=a,n.addEventListener("load",void e[t].appendChild(n)),e[t].addEventListener("click",function(){const e=document.createElement("iframe");e.setAttribute("allowfullscreen",""),e.setAttribute("frameborder","0"),e.setAttribute("src","//www.youtube.com/embed/"+this.dataset.v+"?rel=0&showinfo=0&autoplay=1&iv_load_policy=3&modestbranding=1&noCookie=false&origin=https%3A%2F%2Fwww.xotaku.com&widgetid=1"),this.innerHTML="",this.appendChild(e)})}}();
!function(){const e=document.querySelectorAll(".vplayerold");for(var t=0;t<e.length;t++){console.log(e[t].dataset.v);const a="//i.ytimg.com/vi/"+e[t].dataset.v+"/hqdefault.jpg";var n=new Image;n.src=a,n.addEventListener("load",void e[t].appendChild(n)),e[t].addEventListener("click",function(){const e=document.createElement("iframe");e.setAttribute("allowfullscreen",""),e.setAttribute("frameborder","0"),e.setAttribute("src","//www.youtube.com/embed/"+this.dataset.v+"?rel=0&showinfo=0&autoplay=1"),this.innerHTML="",this.appendChild(e)})}}();
// ]]>
</script>
Adding them in separate script tags should also work, depending what your backend allows you to do.

Embed dynamically updated blog RSS Feed to Website

I have a website on one domain, and a blog hosted on blogspot. at the bottom of the homepage on my website, I want to embed a link to the latest post on my blogspot along with the respective article image and title. I have a function that used to work but since i have moved to blogspot, the RSS url is different from what i previously used, thus the function will not work as expected anymore. How can I work this function around the blogspot rss embed link ?? thanks
blogspot rss2.0 embed link
RSS 2.0: http://blogname.blogspot.com/feeds/posts/default?alt=rss
existing function:
<script src="js/jquery.min.js" type="text/javascript"></script>
<script>
function getRSS(link, number) {
$.ajax(link, {
accepts:{
xml:"application/rss+xml"
},
dataType:"xml",
success:function(data) {
var blogItemArray = $(data).find("item");
var blogItemOne = $(blogItemArray).get(0);
var blogTitleOne = $(blogItemOne).find("title").text();
var blogLinkOne = $(blogItemOne).find("link").text();
var blogDescOne = $(blogItemOne).find("description").text();
var blogImgOne = $(blogDescOne).find("img.hs-featured-image").get();
var blogImgSrcOne = $(blogImgOne).attr("src");
$("#blog-feed-link-" + number).attr("href", blogLinkOne);
$(".vertAlignerImg" + number).append( $('<img class="blog-img-link-'+ number +'" />' ));
$(".blog-img-link-" + number).attr("src", blogImgSrcOne);
$(".vertAligner" + number).append( $('<h2 />', {text: blogTitleOne}) );
}
});
}
$(document).ready(function() {
getRSS('rsslink', "One");
getRSS('rsslink', "Two");
});
</script>
'rsslink' used to be a url that ended in /rss.xml. now it looks like the link above. thanks!

Executing Javascript file from AS 3.0

I am running a small jquery code to my web page:
<!-- myjs.js -->
<script type="text/javascript">
$(document).ready(function() {
$("body").append('<div id="ajaxBusy" class="ajaxBusy"></div>');
</script>
as you can see i am adding a div at my html body with specific class and id name.
How is it possible to execute this .js file throught actionscript 3.0?
I mean to make a flash movie and call this file, or is it possible to execute inline javascript code through AS 3.0?
I found the code bellow but i cant make it work:
import flash.external.ExternalInterface;
var someVarInAS : String = 'foo';
var someOtherVarInAS : int = 10;
var jsXML : XML =
<script type="text/javascript">
var someVarInJS = '{$("body").append('<div id="ajaxBusy" class="ajaxBusy"></div>');}';
var someOtherVarInJS = '{$('#ajaxBusy).fadeIn();}';
<![CDATA[
alert( 'this comes from flash: ' + someVarInJS + ', ' + someOtherVarInJS );
]]>
</script>;
ExternalInterface.call( "function js_" + ( new Date().getTime() ) + "(){ " + jsXML + " }" );
I use this for loading JS files dynamically from AS3 and it works pretty well. Could be modified to run normal js rather than load another file:
var script:String = "" +
"var newscript = document.createElement('script');" +
"newscript.type = 'text/javascript';" +
"newscript.async = true;" +
"newscript.src = 'SomeJavascriptFile.js';" +
"(document.getElementsByTagName('head')[0]||document.getElementsByTagName('body')[0]).appendChild(newscript);";
if ( ExternalInterface.available ) {
ExternalInterface.call("eval", script);
}
You could also avoid having to write javascript within actionscript and keep the two separate in their separate spots. Then just call the method name only using ExternalInterface, instead of calling 'eval' and passing in your javascript. It may be easier to test and maintain down the road.
Inside your html file:
<script>
function addDiv(){
// stuff here that adds the div you want, such as what you had:
$("body").append('<div id="ajaxBusy" class="ajaxBusy"></div>');
}
</script>
Then inside flash:
if (ExternalInterface.available == true) {
ExternalInterface.call("addDiv");
}
You can also supply method arguments from flash to javascript if needed as well.

Extracting the source code of a facebook page with JavaScript

If I write code in the JavaScript console of Chrome, I can retrieve the whole HTML source code by entering:
var a = document.body.InnerHTML; alert(a);
For fb_dtsg on Facebook, I can easily extract it by writing:
var fb_dtsg = document.getElementsByName('fb_dtsg')[0].value;
Now, I am trying to extract the code "h=AfJSxEzzdTSrz-pS" from the Facebook Page. The h value is especially useful for Facebook reporting.
How can I get the h value for reporting? I don't know what the h value is; the h value is totally different when you communicate with different users. Without that h correct value, you can not report. Actually, the h value is AfXXXXXXXXXXX (11 character values after 'Af'), that is what I know.
Do you have any ideas for getting the value or any function to generate on Facebook page.
The Facebook Source snippet is below, you can view source on facebook profile, and search h=Af, you will get the value:
<code class="hidden_elem" id="ukftg4w44">
<!-- <div class="mtm mlm">
...
....
<span class="itemLabel fsm">Unfriend...</span></a></li>
<li class="uiMenuItem" data-label="Report/Block...">
<a class="itemAnchor" role="menuitem" tabindex="-1" href="/ajax/report/social.php?content_type=0&cid=1352686914&rid=1352686914&ref=http%3A%2F%2Fwww.facebook.com%2 F%3Fq&h=AfjSxEzzdTSrz-pS&from_gear=timeline" rel="dialog">
<span class="itemLabel fsm">Report/Block...</span></a></li></ul></div>
...
....
</div> -->
</code>
Please guide me. How can extract the value exactly?
I tried with following code, but the comment block prevent me to extract the code. How can extract the value which is inside comment block?
var a = document.getElementsByClassName('hidden_elem')[3].innerHTML;alert(a);
Here's my first attempt, assuming you aren't afraid of a little jQuery:
// http://stackoverflow.com/a/5158301/74757
function getParameterByName(name, path) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(path);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var html = $('.hidden_elem')[0].innerHTML.replace('<!--', '').replace('-->', '');
var href = $(html).find('.itemAnchor').attr('href');
var fbId = getParameterByName('h', href); // fbId = AfjSxEzzdTSrz-pS
Working Demo
EDIT: A way without jQuery:
// http://stackoverflow.com/a/5158301/74757
function getParameterByName(name, path) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(path);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var hiddenElHtml = document.getElementsByClassName('hidden_elem')[0]
.innerHTML.replace('<!--', '').replace('-->', '');
var divObj = document.createElement('div');
divObj.innerHTML = hiddenElHtml;
var itemAnchor = divObj.getElementsByClassName('itemAnchor')[0];
var href = itemAnchor.getAttribute('href');
var fbId = getParameterByName('h', href);
Working Demo
I'd really like to offer a different solution for "uncommenting" the HTML, but I stink at regex :)

Advert delivery via Javascript document.write

I'm building an advert delivery method and am try to do it through an external Javascript/jQuery page.
I have this so far, but I have some issues with it
$.get('http://url.com/ad.php', {
f_id: _f_id,
f_height: _f_height,
veloxads_width: _f_width
}, function (result) {
var parts = result.split(",");
var path = parts[0],
url = parts[1];
document.write('<img src="' + path + '">');
I can see the page load, but then after the code above is loaded, it creates a new page with just the advert on it. Is there anyway I can write it onto the page where the code was put?
And this is the script web masters put on their websites to include the adverts:
<script type="text/javascript">
var _f_id = "VA-SQ2TDEXO78N0";
var _f_width = 728;
var _f_height = 90;
</script>
<script type="text/javascript" src="http://website.com/cdn/addelivery.js"></script>
Cheers
is ad.php on the same domain as your script? if it's not have a look at this article
here is a code you could use in your html page, where you want the ad to be inserted:
$.get('http://url.com/ad.php',
{ f_id : _f_id, f_height : _f_height, veloxads_width : _f_width }
).success(function(result) {
var parts = result.split(",");
var path = parts[0], url = parts[1];
$('body').prepend('<div id="ad_id"><img src="'+path+'"></div>');
});
the selector (body here) can be an id, a class, ... (see documentation). You can also use prepend() or html() instead of append, to insert the code where you want ;)

Categories