Extracting the source code of a facebook page with JavaScript - 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 :)

Related

Replace elements in a link using javascript

I have a link to add event to google calendar which is populated from a database, but the date is formatted yyyy-mm-dd, and the time hh:mm, and i cannot alter this, but google calendar will not accept.
Can anyone please help me use javascript and the 'replace' function to remove the'-' and ':' from the html please?
<a href="http://www.google.com/calendar/event?
action=TEMPLATE
&text=Tester12
&dates=2014-01-27T22:4000Z/2014-03-20T22:1500Z
&details=Oranges
&location=Newquay
&trp=false
&sprop=
&sprop=name:"
target="_blank" rel="nofollow">Add to my calendar</a>
many thanks.
Fetch the href link from tag and store it in a variable.
var linkStr = "http://www.google.com/calendar/event?action=TEMPLATE&text=Tester12&dates=2014-01-27T22:4000Z/2014-03-20T22:1500Z&details=Oranges&location=Newquay&trp=false&sprop=&sprop=name:";
var re = /&dates=.*?&/g;
var result = re.exec(linkStr);
if(result!=null){
var replaceStr = result[0].replace(/[-|:]/g,'');
var finalLink = linkStr.substr(0,result["index"]) + replaceStr + linkStr.substr(result["index"]+replaceStr.length);
console.log(finalLink);
}else{
alert('link invalid');
}
This will remove all the '-' and ':' from dates parameter string and will store that link in 'finalLink' var.
Hope it helps.
I have been on the sniff for the whole code solution, and witha bit of mix and match, came up with this, AND IT SEEMS TO WORK!!!!!! But please feel free to edit into perfection!
<script>
var linkStr = "http://www.google.com/calendar/event?action=TEMPLATE&text=Example Event&dates=2018-12-16T10:3500Z/2018-12-16T12:0000Z&details=Trip to town&location=No mans land&trp=false&sprop=&sprop=name:";
var re = /&dates=.*?&/g;
var result = re.exec(linkStr);
if(result!=null){
var replaceStr = result[0].replace(/[-|:]/g,'');
var finalLink = linkStr.substr(0,result["index"]) + replaceStr + linkStr.substr(result["index"]+replaceStr.length);
console.log(finalLink);
}else{
alert('link invalid');
}
</script>
Add Event
<script>
(function() {
Array.prototype.forEach.call(document.querySelectorAll("a.finalLink"), function(link) {
link.href = finalLink;
});
})();
</script>

text string output stops after first space, js/html

I apologize in advance, this is the first Stack Overflow question I've posted. I was tasked with creating a new ADA compliant website for my school district's technology helpdesk. I started with minimal knowledge of HTML and have been teaching myself through w3cschools. So here's my ordeal:
I need to create a page for all of our pdf and html guides. I'm trying to create a somewhat interactable menu that is very simple and will populate a link array from an onclick event, but the title="" text attribute drops everything after the first space and I've unsuccessfully tried using a replace() method since it's coming from an array and not static text.
I know I'm probably supposed to use an example, but my work day is coming to a close soon and I wanted to get this posted so I just copied a bit of my actual code.
So here's what's happening, in example 1 of var gmaildocAlt the tooltip will drop everything after Google, but will show the entire string properly with example 2. I was hoping to create a form input for the other helpdesk personnel to add links without knowing how to code, but was unable to resolve the issue of example 1 with a
var fix = gmaildocAlt.replace(/ /g, "&nb sp;")
//minus the space
//this also happens to break the entire function if I set it below the rest of the other variables
I'm sure there are a vast number of things I'm doing wrong, but I would really appreciate the smallest tip to make my tooltip display properly without requiring a replace method.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (i = 0; i < gmailvidTitle.length; i++) {
arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>
Building HTML manually with strings can cause issues like this. It's better to build them one step at a time, and let the framework handle quoting and special characters - if you're using jQuery, it could be:
var $link = jQuery("<a></a>")
.attr("href", gmaildocLink[i])
.attr("title", gmaildocAlt[i])
.html(gmaildocTitle[i]);
jQuery("#gmailList").append($link).append("<br>");
Without jQuery, something like:
var link = document.createElement("a");
link.setAttribute("href", gmaildocLink[i]);
link.setAttribute("title", gmaildocAlt[i]);
link.innerHTML = gmaildocTitle[i];
document.getElementById("gmailList").innerHTML += link.outerHTML + "<br>";
If it matters to your audience, setAttribute doesn't work in IE7, and you have to access the attributes as properties of the element: link.href = "something";.
If you add ' to either side of the variable strings then it will ensure that the whole value is read as a single string. Initially, it was assuming that the space was exiting the Title attribute.
Hope the below helps!
UPDATE: If you're worried about using apostrophes in the title strings, you can use " by escaping them using a . This forces JS to read it as a character and not as part of the code structure. See the example below.
Thanks for pointing this one out guys! Sloppy code on my part.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google's Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
var arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (var i = 0; i < gmailvidTitle.length; i++) {
var arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>

jQuery using Regex to find links within text but exclude if the link is in quotes

I am using jQuery and Regex to search a text string for http or https and convert the string to a URL. I need the code to skip the string if it starts with a quote.
below is my code:
// Get the content
var str = jQuery(this).html();
// Set the regex string
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var replaced_text = str.replace(exp, function(url) {
clean_url = url.replace(/https?:\/\//gi,'');
return '' + clean_url + '';
})
jQuery(this).html(replaced_text);
Here is an example of my issue:
Text The School of Computer Science and Informatics. She blogs at http://www.wordpress.com and can be found on Twitter #Abcdef.
The current code successfully finds the text that starts with http or https and converts it to a URL but it also converts the twitter URL. I need to ignore the text if it starts with a quote or is within an a tag, etc...
Any help is much appreciated
What about adding [^"'] to the exp variable?
var exp = /(\b[^"'](https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
Snippet:
// Get the content
var str = jQuery("#text2replace").html();
// Set the regex string
var exp = /(\b[^"'](https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var replaced_text = str.replace(exp, function(url) {
clean_url = url.replace(/https?:\/\//gi,'');
return '' + clean_url + '';
})
jQuery("#text2replace").html(replaced_text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text2replace">
The School of Computer Science and Informatics. She blogs at http://www.wordpress.com and can be found on Twitter #Abcdef.
</div>
If you really just want to ignore the quotation marks, this could help:
var replaced_text = $("#selector").html().replace(/([^"])(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig, '$1$2');
This works for me:
This will recognize urls and convert them to hyperlinks, but will ignore urls, wrapped in " (quotes).
See the code below or this jsfiddle for a working example.
Example HTML:
<ul class="js-replaceUrls">
<li>
www.link-only-www.com
</li>
<li>
http://link-starts-with-HTTP.com
</li>
<li>
https://www.link-starts-with-https-and-www.com
</li>
<a href="https://link-starts-with-https.com">
Link in anchor tag
</a>
</ul>
RegEX:
/(([a-z]+:\/\/)?(([a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal))(:[0-9]{1,5})?(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:#/?]*)?)(\s+|$)/gmi
jQuery:
// RECOGNIZE URLS AND CONVERT THEM TO HYPERLINKS
// Ignore if hyperlink is found in HTML attr, like "href"
$('.js-replaceUrls').each(function(){
// GET THE CONTENT
var str = $(this).html();
// SET THE REGEX STRING
var regex = /(([a-z]+:\/\/)?(([a-z0-9\-]+\.)+([a-z]{2}|aero|arpa|biz|com|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|local|internal))(:[0-9]{1,5})?(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-zA-Z0-9!$&'()*+.=-_~:#/?]*)?)(\s+|$)/gmi;
// REPLACE PLAIN TEXT LINKS BY HYPERLINKS
var replaced_text = str.replace(regex, "<a href='$1' class='js-link'>$1</a>");
// ECHO LINK
$(this).html(replaced_text);
});
// DEFINE URLS WITHOUT "http" OR "https"
var linkHasNoHttp = $(".js-link:not([href*=http],[href*=https])");
// ADD "http://" TO "href"
$(linkHasNoHttp).each(function() {
var linkHref = $(this).attr("href");
$(this).attr("href" , "http://" + linkHref);
});
See this jsfiddle for a working example.

jQuery insert/remove text at specific position in input field/textarea

I am trying to do similar thing as YouTube has when you are embeding a video and you want to get a code. You can click on checkboxes or select size and it dynamically changes the value of input field.
Does somebody have idea how to do it?
I managed to write a code that is replacing the width correctly, but I dont know how to make a code that would add &scheme=XXX at the end of the link or remove it if user selects no color scheme.
This is the code for width,I dont think its best one, but works:
$("#width").on("change keyup", function(){
var width = $(this).val();
if (width){
$("#embed-text").val($("#embed-text").val().replace(/ (width\s*=\s*["'])[0-9]+(["'])/ig, ' width=\''+width+'\''));
}
});
Here is textarea which I am trying to change and inputs I'm using for it:
The ID is taken from PHP, in actual textarea that jQuery sees the ".$id." is actual number
<textarea class='clean' id='embed-text'><iframe src='http://my.url/embed/?r=".$id."' width='600' height='".$height."' frameborder='0' marginwidth='0' marginheight='0' allowtransparency='true'></iframe></textarea>
<div style='padding-right: 10px; display: inline-block;'>
Color scheme:
<select id='schemes' class='clean'>
<option value='-'>None</option>
<option value='xxx'>Xxx</option>
</select>
</div>
<div style='padding-right: 10px; display: inline-block;'>
Width: <input type='number' min='250' max='725' value='600' id='width' class='clean'>
</div>
When user does not select any scheme (or changes from XXX to None), I want link in textarea (iframes src) to be like this:
http://my.url/embed/?r=X
But when he selects any scheme, i would like it to look like this:
http://my.url/embed/?r=X&scheme=XXX
I actually have no idea how to do this. Tried googling for more than hour, but I don't know what the ID will be (to identify position where to add the string), thats PHP value and I cant pass it to external script file, so I tried to find if I can insert something at specific position (ie.: 15th character from start) with JS, but could not find anything.
Thanks.
I separate some functions in order to keep the code clean check this I think that is what you were looking for JsFiddle
var generateUrl = function(id,colorScheme) {
var baseUrl = "http://my.url/embed/?";
var url = baseUrl.concat("r="+id);
if (colorScheme != null && colorScheme != '')
url = url.concat("&scheme="+colorScheme);
return url;
};
var changeUrl = function(id, colorScheme) {
var url = generateUrl(id, colorScheme);
var srcPattern = "src='(.*?)'";
var embedText = $("#embed-text").val();
var newEmbedText = embedText.replace(new RegExp(srcPattern),"src='"+url+"'");
$("#embed-text").val(newEmbedText);
};
var changeWidth = function(newWidth) {
var widthPattern = "width='([0-9]*)'";
var embedText = $("#embed-text").val();
var newEmbedText = embedText.replace(new RegExp(widthPattern),"width='"+newWidth+"'");
$("#embed-text").val(newEmbedText);
};
var getURLParameter = function(url,parameterName) {
return decodeURIComponent((new RegExp('[?|&]' + parameterName + '=' + '([^&;]+?)(&|#|;|$)').exec(url)||[,""])[1].replace(/\+/g, '%20'))||null
};
var getId = function() {
var urlPattern = "src='(.*?)'";
var embedText = $("#embed-text").val();
var url = embedText.match(new RegExp(urlPattern))[1];
var id = getURLParameter(url, 'r');
return id;
};
$("#width").on("change keyup", function(){
var width = $(this).val();
var colorScheme = $(schemes).val();
changeWidth(width);
changeUrl(getId(),colorScheme);
});
And i removed the value '-' for the first option just leave it in blank.

JavaScript Error when Showing iFrame

I am passing values within a url to an iframe - on a coldfusion website. However, the iframe isn't appearing on the page. I have a method that I have used on a previous website, non-coldfusion, and this works perfectly - which leads me to believe that the issue is caused by the site being coldfusion. I have no experience with ColdFusion.
Hopefully, if I show you the code I am using to pull in the iFrame and values, somebody may be able to help me out - which would be greatly appreciated....
<script language="javascript">
function gup(name){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null ) return ""; else return unescape(results[1]);
}
function prepare() { document.getElementById('EMAIL_FIELD').innerHTML = gup('email');
var email = gup('email');
document.getElementById('FIRSTNAME_FIELD').innerHTML = gup('firstname');
var firstname = gup('firstname');
document.getElementById('LASTNAME_FIELD').innerHTML = gup('lastname');
var lastname = gup('lastname');
document.getElementById('COUNTRY_FIELD').innerHTML = gup('country');
var country = gup('country');
document.getElementById('frame').innerHTML = "<iframe src='http://webe.emv3.com/tennisexpress/pref_center/Tennis_SP.html?email="+email+"&firstname="+firstname+"&lastname="+lastname+"&country="+country+"' width='750' scrolling='no' height='1000' frameborder='0' ></iframe>";
}
The body tag has the following onLoad function:
<body onLoad="javascript:prepare();">
and the iFrame is called as:
<div id="frame"></div>
if you use the following url, you will see that the iFrame is not shown:
http://www.tennisexpress.com/newsletter_signup.cfm?email=grozanski#emailvision.com&zipcode=11206&source=homepage&firstname=Gary&lastname=Rozanski&country=ny
Am I missing something obvious? Can anyone recommend any changes?
Firebug shows a JavaScript error:
document.getElementById("FIRSTNAME_FIELD") is null
[Переривати на цій помилці] documen...IELD').innerHTML = gup('firstname');
Possibly it's the reason of iframe not being created.

Categories