I'm trying to dynamically set the thumbnail shown when sharing to Facebook using javascript. I tried adding the meta tag "og:image" to the page (it's a JSP) and that works, but what I want to do now is to replace such image with another one dynamically loaded by javascript.
Basically, the page is calling an API upon loading, using javascript, and retrieves a list of images. I want to use one of those as the thumbnail.
I tried using javascript to replace the content of the meta tag, but Facebook doesn't seem to care abou t it (it does change if I check with my browser).
Is it possible to do this?
Thanks in advance!
Here is a function I used to extract the image url from a flash object tag's flashvars parameter, and then assign it to a meta tag by using jquery:
$(window).load(function(){
//Use $(window).load() instead of $(document).ready(), so that the flash code has loaded and you have all the html you need process with javascript already in place when you start processing.
var stringToExtractFrom = $('param[name="flashvars"]').attr('value');
//Get the flashvars parameter value which we'll use to extract the preview image url from.
var pos = stringToExtractFrom.indexOf("&");
//Search for the position ampersand symbols which surround the image url.
var stringToUse;
//The final string we'll use.
var startOfImageSrc = null;
//The first position where we discover the ampersand
var endOfImageSrc;
//The second position where we discover the ampersand
var lengthToSubstract
//How many symbols to chop off the flashvars value.
while(pos > -1) {
if(startOfImageSrc == null){
startOfImageSrc = pos;
}
else {
endOfImageSrc = pos;
lengthToSubstract = endOfImageSrc - startOfImageSrc;
}
pos = stringToExtractFrom.indexOf("&", pos+1);
}
stringToUse = stringToExtractFrom.substr(startOfImageSrc+7, lengthToSubstract-7);
$('meta[property="og:image"]').attr('content', stringToUse); });
Facebook robot never runs a java script code
but why you don't try to set og tags in in server-side ?
Related
My webpage contains some RSS feeds from some random sites.
There are links within these feeds which take you to these sites. Is there anyway to load these webpages into a div on my page?
The problem Im having is that these RSS links are created dynamically when I create my RSS feeds.
Dose anyone have any suggestions?
function showLTab(key)
{
var myObject = science[key];
var stage = $("#leftFeed").children('#tabContent');
//forming the query
//LIMT controls amount of tabs displayed in each feed
var query = "select * from feed where url='"+myObject.feed+"' LIMIT 5";
//changing URL to YQL
var url = "http://query.yahooapis.com/v1/public/yql?q="+encodeURIComponent(query)+"&format=json&callback=?";
$.getJSON(url,function(data){
//removes any previous feeds
stage.empty();
//item exists in RSS
$.each(data.query.results.item || data.query.results.entry,function(){
stage.append(myObject['function'](this));
})
});
$("#leftFeed").children('#activeTab').text(key);
}
function showLeftDropDown()
{
var activeTab = $("#leftFeed").children('#activeTab');
//creating drop down div
var dropDown = $('<div>').addClass('dropDownList').css({'top': 10, 'width': activeTab.width()}).hide().appendTo('#leftFeed');
$.each(science,function(i){
// populates dropdown div
if(i==activeTab.text()) return true;
$('<div>').text(i).appendTo(dropDown);
})
dropDown.slideDown('fast');
}
use this jquery
https://github.com/sdepold/jquery-rss
it will help u
If you know the URL of the page that interests you (that is to say, this question is about the display of the page and not the retrieval of the links) and simply want to spit out the result into a container such as a div, you can do this:
$("#myDiv").load("page url");
This passes an Ajax request to the given url and loads the content into the selected element. See http://api.jquery.com/load/ for more info.
Another option is using iframes. You can create an iframe and then set the src property to the url that you are interested in using JavaScript:
document.getElementById("myIframe").src = "page url";
Okay, so if you don't know the URL but have the feed that you can parse, try a regex. Given that links look like this:
<link>http://www.someexamplerssdomain.com/main.html</link>
You can use this code to parse them all out into an array:
var regex = /<link>(.*?)<\/link>/gi;
var matches = new Array();
var match = regex.exec(rssInput);
while (match != null) {
matches.push(match[1]);
match = regex.exec(rssInput);
}
You can then use either of the two methods I first suggested to retrieve their content.
I'm making a websites that displays noise measurement data from different locations. The data for each location is captured on a sound level meter device and it is then read with a windows-based application. The application then uploads data on a web server as a .js file with an array variable in it. This .js files are refreshed every 5 minutes.
I first created a javascript application that displays live data for a single measuring unit. But now I need to display data on a map for all the locations. The problem is that the windows application on each location makes a file with the same name and same variables only on another location. I'm having some trouble with reading the correct data.
This is what I did so far:
function removejscssfile(filename, filetype){
var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
var allsuspects=document.getElementsByTagName(targetelement)
for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
}
}
function updateData(){
var numberOfNoiseSniffers = noiseSniffers.length-1;
var j = 0;
for (i=0;i<=numberOfNoiseSniffers;i++) {
file = '../'+ noiseSniffers[i] + "/" + "CurrentMeasurement.js";
$.include(file,function(){
laeq[j] = currentMeas[1][1];
lastUpdate[j] = currentMeas[0][1];
if (j==numberOfNoiseSniffers){
updateMarkers();
}
removejscssfile(file[0], "js");
j++;
});
}
t=setTimeout(function() { updateData() }, 300000);
}
$(function (){
map = new google.maps.Map(document.getElementById("gMap"), myOptions);
//noiseSniffers is an array where I have save all the folder names of different measurement locations
var numberOfNoiseSniffers = noiseSniffers.length-1;
var j = 0;
for (i=0;i<=numberOfNoiseSniffers;i++) {
var file = '../'+ noiseSniffers[i] + "/" + "CurrentMeasurement.js";
//I am using include plugin for jquery to include files because it has a callback for when a file is actually loaded
$.include(file,function(){
//a set of global arrays that keep the data from the loaded file and this data is then displayed in google maps markers
laeq[j] = currentMeas[1][1];
lastUpdate[j] = currentMeas[0][2];
latitude[j] = systemstats[12][5];
longitude[j] = systemstats[11][6];
//checking to see if I am in the process of including the last file
if (j==numberOfNoiseSniffers){
//a function that creates google maps markers
createMarkers();
}
//after that I remove the files that were just included and read
removejscssfile(file, "js");
j++;
});
}
setTimeout(function() { updateData() }, 300000);
});
I got the function for removing my .js file here: Dynamically removing an external JavaScript or CSS file.
And this is the jquery plugin for loading the .js file: Include File On Demand.
The initial load usually works (sometimes it happens that only one or no markers get loaded. But the update function mostly returns the same data for both locations.
So what I want to know is, how can I firstly make my code working and how to optimize it. I posted just the main parts of the javascript code, but I can provide all the code if it is needed. Thanks for any help.
I think you need some sort of JSONP-like solution.
Basically load data on the server side, then wrap it in a method call before returning it to client side. Your response should look something like this:
var location_data = [1,2,3,4]
updateLocation('location_id', location_data)
Now you define an updateLocation() function in your client side script. Now, every time you need new data, you create new 'script' tag with src pointing to your server side. When the response is loaded, your updateLocation() will be invoked with correct params.
I hope this is clear enough
You can maybe try some form of namespacing
i exactly dont understood your problem, but you may try this
//put your code inside an anonymous function and execute it immediately
(function(){
//your javascript codes
//create variable with same names here
//
})();
I am creating a webapp and I have been using tag in my JSPs to ensure that all my links (both to pages and to resources such as images/css) are always consistent from the root of the application, and not relative to my current location.
Some of the content I am creating using jQuery, for example, I am creating a HTML table by parsing a JSON object and using jquery.append() to insert it in to a div.
My question is, if I want to dynamically create a link using jquery how can I achieve a consistent URL regardless of the page being executed? I have tried just building the html with the tag in it, but no joy.
Thanks!
var baseURL = "/* Server-side JSP code that sets the base URL */";
$("<a />", { href: baseURL+"/my/resource/here.jsp" }); //Your proper link
Or you could do:
var baseURL = "http://"+location.host+"/my/base/url/";
//Which gives you something like http://mySite.com/my/base/url/
Get the root value of your webapp into a string using a jsp tag inside your javascript.
var root = < %=myRootVariable%> //This evaluates to http://www.myapp.com
var dynamicBit = "/foo/bar"
var dynamicLinkUrl = root + dynamicBit
var $newa = $("Hello, world");
$someJQElement.append($newa)
Hopefully none of this will occur in the global namespace. Just sayin'
Let's say I have a web page (/index.html) that contains the following
<li>
<div>item1</div>
details
</li>
and I would like to have some javascript on /index.html to load that
/details/item1.html page and extract some information from that page.
The page /details/item1.html might contain things like
<div id="some_id">
picture
map
</div>
My task is to write a greasemonkey script, so changing anything serverside is not an option.
To summarize, javascript is running on /index.html and I would
like to have the javascript code to add some information on /index.html
extracted from both /index.html and /details/item1.html.
My question is how to fetch information from /details/item1.html.
I currently have written code to extract the link (e.g. /details/item1.html)
and pass this on to a method that should extract the wanted information (at first
just .innerHTML from the some_id div is ok, I can process futher later).
The following is my current attempt, but it does not work. Any suggestions?
function get_information(link)
{
var obj = document.createElement('object');
obj.data = link;
document.getElementsByTagName('body')[0].appendChild(obj)
var some_id = document.getElementById('some_id');
if (! some_id) {
alert("some_id == NULL");
return "";
}
return some_id.innerHTML;
}
First:
function get_information(link, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", link, true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(xhr.responseText);
}
};
xhr.send(null);
}
then
get_information("/details/item1.html", function(text) {
var div = document.createElement("div");
div.innerHTML = text;
// Do something with the div here, like inserting it into the page
});
I have not tested any of this - off the top of my head. YMMV
As only one page exists in the client (browser) at a time and all other (virtual/possible) pages are on the server, how will you get information from another page using JavaScript as you will have to interact with the server at some point to retrieve the second page?
If you can, integrate some AJAX-request to load the second page (and parse it), but if that's not an option, I'd say you'll have to load all pages that you want to extract information from at the same time, hide the bits you don't want to show (in hidden DIVs?) and then get your index (or whoever controls the view) to retrieve the needed information from there ... even though that sounds pretty creepy ;)
You can load the page in a hidden iframe and use normal DOM manipulation to extract the results, or get the text of the page via AJAX, grab the part between <body...>...</body>ยจ and temporarily inject it into a div. (The second might fail for some exotic elements like ins.) I would expect Greasemonkey to have more powerful functions than normal Javascript for stuff like that, though - it might be worth to thumb through the documentation.
I need to show a DIV on two pages (URL's) but not on the others.
(I have jQuery on the pages if that helps.). I'm a complete noob so all help is very much appreciate. Thank's!
Case (1) where I want to show the DIV:
On the start page, when the web browser address field reads 'www.mydomin.com'
The start page is PHP so I guess the full URL is 'www.mydomin.com/index.php'
Case (2):
'www.mydomin.com/index.php?option=com_myblog&title.html&Itemid=1&lang=en'
WHERE this part is alway the same
'www.mydomin.com/index.php?option=com_myblog&'
AND this part is always unique
'title.html&Itemid=1&lang=en
Example
if (url == 'www.mydomin.com' or 'www.mydomin.com/index.php?option=com_myblog&') {
do this
xxxxxxxx
else
nothing
This should work, if I understand the question correctly
var url = document.location.href;
if (url.indexOf('www.mydomin.com/index.php?option=com_myblog&') >= 0) {
$('#div_id').hide();
} else {
$('#div_id').show();
}
But really, if you use PHP anyway, you should figure out how to not render the div in the first place.
You can parse the query string and show/hide the div based on the result.
I also think it should be handled from PHP code instead from JavaScript. And div should not be rendered in first place.
You can target a specific query parameter of the URL using window.location.search. Using the below code, you can find an exact match anddisplay/hide the HTML element:
var firstURLParam = window.location.search.substring(1).split('&')[0];
var datGuiEle = document.getElementById("elemID");
if(firstURLParam == "debug"){
datGuiEle.style.display = "block";
}
else {
datGuiEle.style.display = "none";
}