Reading HTML header info of files via JS - javascript

I have a product list that is generated by asp
I have product description for each product in a html file
each html file is named: <product.id>.html<br/>
html file size is only 1-3 kb
Within the html file is <title> and <meta name="description" content="..." />
I want to access these in an efficient way so that I can output this as e.g.:
document.write(<product.id>.html.title);<br/>
document.write(<product.id>.html.description);
I have a working solution for the individual product, where I use the description file - but hope to find a more efficient / simple approach. Preferably, I want to avoid having 30+ hidden iframes - google might think that I am trying to tamper with search result and blacklist my page...
Current code:
<iframe src="myfile.html" id="product" style="display:none"> </iframe>
<script type="text/javascript">
document.getElementById('product').onload = function(){
var d = window.frames[frame].document;
var title = d.title : ' ';
var keywords = d.getElementsByName('keywords')[0].getAttribute('content', 0) : ' ';
var descript = d.getElementsByName('description')[0].getAttribute('content', 0) : ' ';
}
</script>

As mentioned here on another Stack Overflow question, you could use:
document.title = "This is the new page title.";
and looking here gives us :
document.getElementsByTagName('meta').content = "New content here";
or:
document.getElementsByTagName('meta').name = "NewName";
With these, you should be able to read and write your tags as needed, I've only used a few examples here, there's surely more.

You could load your files with AJAX. For example (using jQuery):
$.get('myfile.html', function(data){
var title = $(data).find('head title').text();
var keywords = $(data).find('head meta[name="keywords"]').attr('content');
var descript = $(data).find('head meta[name="description"]').attr('content');
});
Here you find the jQuery documentation about using jQuery.get

Found this solution:
<script>
var xhr = $.ajax({
type: "GET",
url: "/files/billeder/ecom/beskrivelser/<!--#Ecom:Group.Number-->.html",
success: function(msg){
msg = msg.split('content="')[1];
msg = msg.split('"')[0];
document.getElementById("a_<!--#Ecom:Group.Number-->").innerHTML = "<p>" + msg + "</p>";
Not yet very elegant... but it works...

Related

Display song's metadata in page title (browser tab)?

I would label my coding skills as intermediate thus what I am asking may or may not be simple or obvious (I wouldn't know the difference). Also I sincerely thank any and everyone who gives this even an ounce of attention.
My objective is to grab raw song metadata from another server (in which I am a client of) via the jsonp and ajax method. Once I successfully obtain the metadata (Artist, Title & album), I then would like to display it in my website’s page title (please see pics below).
The reason I would like to do this is because from what I could gather via an extensive and worn out research, it seems that most Bluetooth Audio devices are reading the metadata from the page title (browser tab):
Google Music playing in browser
BT Audio player
What I would love to do seems like it should be simple to do, yet I cannot figure away to display "Artist, Title and Album" in my browser like Spotify, Youtube or Google Music does.
My code below is able to pull the raw data, convert it using jsonp and I can successfully push only ONE element from the raw data (IE 'title') by placing it as an ID element. However, how can I push all three (Artist, Title & Album) to the page title?
<!DOCTYPE html>
<html
lang=en
dir="ltr"
class="mobile-web-player"
>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
function update(metadataObj) {
if (metadataObj && metadataObj.m_Item2) {
var title = document.getElementById('title');
title.innerHTML = metadataObj.m_Item2.Title;
var artist = document.getElementById('artist');
artist.innerHTML = 'by ' + metadataObj.m_Item2.Artist;
var album = document.getElementById('album');
album.innerHTML = metadataObj.m_Item2.Album + ' ';
}
}
</script>
<script type="text/javascript">
var stationID = 'X123';
var apiToken = 'X12345';
// refresh MetaData every 5 seconds
function fetchMetadata(stationID, apiToken) {
$.ajax({
type: 'get',
cache: false,
url: "https://listen.samcloud.com/webapi/station/X123/history/npe?token=X12345&callback=update&format=json",
//async: true,
datatype: 'jsonp',
});
}
fetchMetadata(stationID, apiToken);
window.setInterval(function() {
fetchMetadata(stationID, apiToken);
}, 5000);
</script>
<!-- I can successfully send the song's title to my page title via <title id> method -->
<title id="title">My Radio Station</title>
</head>
<body>
</body>
</html>
In your update() function you can call document.title to set the new tab title instead of setting the <title> tag. For example:
function update(metadataObj) {
if (metadataObj && metadataObj.m_Item2) {
var title = document.getElementById('title');
var artist = document.getElementById('artist');
var album = document.getElementById('album');
// If you are using es6
document.title = `Playing ${title} from ${artist} - ${album}`;
// If not using es6
// document.title = 'Playing '+ title + ' from '+ artist +' - album';
}
}
You could change your update function to the following to write Artist, Title, and Album to the web pages title.
function update(metadataObj) {
if (metadataObj && metadataObj.m_Item2) {
var title = document.getElementById('title');
title.innerHTML = metadataObj.m_Item2.Title + ' ' + metadataObj.m_Item2.Album + ' ' + metadataObj.m_Item2.Artist;
}
}

How to Reference XML File/Data to be Used with HTML and jQuery?

So I have an XML file, that I generated from an Excel file. Each item looks like this:
<item>
<partnum>pn0001</partnum>
<category>Parent Category</category>
<title>Item Name Here</title>
<type>T27</type>
<diameter>6"</diameter>
<width>0.045"</width>
<arbor>7/8"</arbor>
<material>Metal</material>
<maxrpm>13300</maxrpm>
<tool>Angle Grinder</tool>
<purpose>Cutting</purpose>
<brand>Brand Name Here</brand>
<imgsrc>localfolder\file.jpg</imgsrc>
</item>
I'd like to be able to reference this data, and create variables for each of the items. Obviously, I'll have to write a loop that will go through each item, and store the data. It will end up being something like pn0001.category, pn0001.title. etc, etc.
My question is: how do I begin to reference the XML file? I ran across this link: https://api.jquery.com/jQuery.parseXML/
Which is great, but in the code, you'll see that they have the XML data hard-coded as a string in the first variable.
Basically, how do I get the data from the XML into variables in either Javascript or jQuery?
Here is a jquery example
var xml = '<?xml version="1.0" encoding="UTF-8"?><items><item><partnum>pn0001</partnum><type>T27</type><material>Metal</material></item><item><partnum>pn0002</partnum><type>T28</type><material>plastic</material></item></items>';
var xmlDoc = $.parseXML(xml);
var $xml = $(xmlDoc);
$xml.find('item').each(function(index) {
var partnum = $(this).find('partnum').text();
var type = $(this).find('type').text();
var material = $(this).find('material').text();
$('<span>' + partnum + ' ' + type + ' ' + material + '</span><br>').appendTo('#output');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>

Why is HTML elements is displayed as text?

I'm working on a form builder website. After a form is built it must be saved in database. When the user clicks on a form name from the list of saved forms the form information is restored from database. One of the variables I will restore is the structure of the form. In javascript I wrote these lines of code:
var prefix_content='<!DOCTYPE HTML>\n<html lang="en-US">\n<head>\n<meta charset="UTF-8">\n<title> </title>\n </head>\n<body>\n ';
var sufex_content=' \n</body></html>';
var dynamic_content=String(text_content);
document.write(prefix_content + dynamic_content + sufex_content );
The variable dynamic_content contains the dynamic structure.
The problem is that prefix_content and sufex_content is displayed as html but dynamic_content is written in the page as text. Any one knows why is that or knows how to solve this problem.
Note: when I write the text in dynamic content statically between single quotes it is displayed as html not text.
If you're seeing the content retrieved from your database as plaintext, instead of HTML, its HTML entities are probably getting escaped somewhere along the way. Check the contents of your text_content variable (e.g. use console.log(text_content) and if you're seeing stuff like <div> instead of <div>, go on and find out where your escaping happens and either remove it or manually unescape.
TRY THIS:
var prefix_content='<!DOCTYPE HTML>\n<html lang="en-US">\n<head>\n<meta charset="UTF-8">\n<title> </title>\n </head>\n<body>\n ';
var sufex_content=' \n</body></html>';
var dynamic_content=String(text_content);
var parser = new DOMParser();
var el = parser.parseFromString(dynamic_content, "text/html");
document.write(prefix_content + el + sufex_content );
Or you can try this too: Using jQuery
var dynamic_content=String(text_content);
var el = $.parseHTML( dynamic_content );
document.write(prefix_content + el + sufex_content );
var content = "<div style='color:red;'>TEST</div>";
var prefix ='<!DOCTYPE HTML>\n<html lang="en-US">\n<head>\n<meta charset="UTF-8">\n<title>TEST</title>\n</head>\n<body>\n';
var suffix ='\n</body></html>';
var all = prefix + content + suffix;
var parser = new DOMParser();
var doc = parser.parseFromString(all, "text/html");
console.log(doc.children[0].outerHTML);
Instead of children[0] you can also go for:
doc.documentElement.outerHTML
Results in:
<html lang="en-US"><head>
<meta charset="UTF-8">
<title>TEST</title>
</head>
<body>
<div style="color:red;">TEST</div>
</body></html>

Adding javascript variable to hyperlink within script

I have been trying to create a hyperlink using a variable defined earlier in the same function to append:
var NAMEVARIABLE = responseArray[i].Name;
var TITLE_Game = document.createElement("p");
TITLE_Game.className = "TITLE_Game";
TITLE_Game.innerHTML = "<a href='Game_NAMEVARIABLE.html'>Games</a>";
I have tried the following using the solution found here: Passing Javascript variable to <a href >
Games
But that didn't work. I then tried adding an ID:
<a id="link" href="Game_.html?propid=">Games</a>
And adding this to the script: document.links["link"].href += NAMEVARIABLE;
This didn't work either. These links are occuring within Isotope, which I've run into newbie-problems making sure my JSON data is loading before the script executes. That's all working now, but I'm not sure if the reason the above methods aren't working is because of a similar issue, or if they simply are not the proper way to go about this.
Any help is much appreciated. Thank you
first of all, try debug your variable :
var NAMEVARIABLE = responseArray[i].Name;
alert(NAMEVARIABLE);
is it returning the desired return value or not.
and then the second thing, in your first style of script, try this instead :
TITLE_Game.innerHTML = "<a href='Game_"+NAMEVARIABLE+".html'>Games</a>";
I assumed you have (static) html collection with game_[number_id].html format
and if it's so, you can try further with your second style of script, and change it to this :
Games
you need to learn further about javascript strings concatenation
Use string concatenation to build up your inner html string.
Example:
var nameVariable = 'Foo';
var innerHtmlText = nameVariable + 'bar';
$('#someElement').html(innerHtmlText);
The contents of someElement will then contain the text: 'Foobar';
You just need string concatenation. modify link's href onclick would be considered as spam in most modern browser.
<div id="result">
the result:
</div>
<script type="text/javascript">
var name = "foo_bar";
var url = "page.html?key=" + name; //or.. "page_" + name + ".html";
var link = 'link here';
$("#result").addClass("g_title");
$("#result").append(link);
</script>
This can be achieved by either (i.e. pure JS or jQuery) ways without much hassle. Suppose you have this <a> element with some href
<a id="Link" href="/collection/categories/">Games</a>
Pure JavaScript way:
window.onload = function() {
var link= document.getElementById('Link'),
url = link.href + responseArray[i].Name + '.html';
link.setAttribute('href', url);
}
Using Jquery:
$(function(){
var link= $('#Link'),
url = link.attr('href') + responseArray[i].Name + '.html';
link.attr('href', url);
});

How can i rerender Pinterest's Pin It button?

I'm trying to create and manipulate the Pin It button after page load. When i change the button properties with js, it should be rerendered to get the functionality of pinning dynamically loaded images. So, does Pinterest have any method like Facebook's B.XFBML.parse() function?
Thanks...
Just add data-pin-build attribute to the SCRIPT tag:
<script defer
src="//assets.pinterest.com/js/pinit.js"
data-pin-build="parsePinBtns"></script>
That causes pinit.js to expose its internal build function to the global window object as parsePinBtns function.
Then, you can use it to parse links in the implicit element or all of the links on the page:
// parse the whole page
window.parsePinBtns();
// parse links in #pin-it-buttons element only
window.parsePinBtns(document.getElementById('pin-it-buttons'));
Hint: to show zero count just add data-pin-zero="1" to SCRIPT tag.
The best way to do this:
Remove the iframe of the Pin It button you want to manipulate
Append the html for the new button manipulating it as you wish
Realod their script - i.e. using jQuery:
$.ajax({ url: 'http://assets.pinterest.com/js/pinit.js', dataType: 'script', cache:true});
To render a pin-it button after a page has loaded you can use:
<a href="..pin it link.." id="mybutton" class="pin-it-button" count-layout="none">
<img border="0" src="//assets.pinterest.com/images/PinExt.png" width="43" height="21" title="Pin It" />
</a>
<script>
var element = document.getElementById('mybutton');
(function(x){ for (var n in x) if (n.indexOf('PIN_')==0) return x[n]; return null; })(window).f.render.buttonPin(element);
</script>
Assuming of course the assets.pinterest.com/js/pinit.js is already loaded on the page. The render object has some other useful methods like buttonBookmark, buttonFollow, ebmedBoard, embedPin, embedUser.
I built on Derrek's solution (and fixed undeclared variable issue) to make it possible to dynamically load the pinterest button, so it can't possibly slow down load times. Only tangentially related to the original question but I thought I'd share anyway.
at end of document:
<script type="text/javascript">
addPinterestButton = function (url, media, description) {
var js, href, html, pinJs;
pinJs = '//assets.pinterest.com/js/pinit.js';
//url = escape(url);
url = encodeURIComponent(url);
media = encodeURIComponent(media);
description = encodeURIComponent(description);
href = 'http://pinterest.com/pin/create/button/?url=' + url + '&media=' + media + '&description=' + description;
html = '<img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" />';
$('#pinterestOption').html(html);
//add pinterest js
js = document.createElement('script');
js.src = pinJs;
js.type = 'text/javascript';
document.body.appendChild(js);
}
</script>
in document ready function:
addPinterestButton('pageURL', 'img', 'description');//replace with actual data
in your document where you want the pinterest button to appear, just add an element with the id pinterestOption, i.e.
<div id="pinterestOption"></div>
hope that helps someone!
Here's what I did.
First I looked at pinit.js, and determined that it replaces specially-marked anchor tags with IFRAMEs. I figured that I could write javascript logic to get the hostname used by the src attribute on the generated iframes.
So, I inserted markup according to the normal recommendations by pinterest, but I put the anchor tag into an invisible div.
<div id='dummy' style='display:none;'>
<a href="http://pinterest.com/pin/create/button/?
url=http%3A%2F%2Fpage%2Furl
&media=http%3A%2F%2Fimage%2Furl"
class="pin-it-button" count-layout="horizontal"></a>
</div>
<script type="text/javascript" src="//assets.pinterest.com/js/pinit.js">
</script>
Then, immediately after that, I inserted a script to slurp up the hostname for the pinterest CDN, from the injected iframe.
//
// pint-reverse.js
//
// logic to reverse-engineer pinterest buttons.
//
// The standard javascript module from pinterest replaces links to
// http://pinterest.com/create/button with links to some odd-looking
// url based at cloudfront.net. It also normalizes the URLs.
//
// Not sure why they went through all the trouble. It does not work for
// a dynamic page where new links get inserted. The pint.js code
// assumes a static page, and is designed to run "once" at page creation
// time.
//
// This module spelunks the changes made by that script and
// attempts to replicate it for dynamically-generated buttons.
//
pinterestOptions = {};
(function(obj){
function spelunkPinterestIframe() {
var iframes = document.getElementsByTagName('iframe'),
k = [], iframe, i, L1 = iframes.length, src, split, L2;
for (i=0; i<L1; i++) {
k.push(iframes[i]);
}
do {
iframe = k.pop();
src = iframe.attributes.getNamedItem('src');
if (src !== null) {
split = src.value.split('/');
L2 = split.length;
obj.host = split[L2 - 2];
obj.script = split[L2 - 1].split('?')[0];
//iframe.parentNode.removeChild(iframe);
}
} while (k.length>0);
}
spelunkPinterestIframe();
}(pinterestOptions));
Then,
function getPinMarkup(photoName, description) {
var loc = document.location,
pathParts = loc.pathname.split('/'),
pageUri = loc.protocol + '//' + loc.hostname + loc.pathname,
href = '/' + pathToImages + photoName,
basePath = (pathParts.length == 3)?'/'+pathParts[1]:'',
mediaUri = loc.protocol+'//'+loc.hostname+basePath+href,
pinMarkup;
description = description || null;
pinMarkup = '<iframe class="pin-it-button" ' + 'scrolling="no" ' +
'src="//' + pinterestOptions.host + '/' + pinterestOptions.script +
'?url=' + encodeURIComponent(pageUri) +
'&media=' + encodeURIComponent(mediaUri);
if (description === null) {
description = 'Insert standard description here';
}
else {
description = 'My site - ' + description;
}
pinMarkup += '&description=' + encodeURIComponent(description);
pinMarkup += '&title=' + encodeURIComponent("Pin this " + tagType);
pinMarkup += '&layout=horizontal&count=1">';
pinMarkup += '</iframe>';
return pinMarkup;
}
And then use it from jQuery like this:
var pinMarkup = getPinMarkup("snap1.jpg", "Something clever here");
$('#pagePin').empty(); // a div...
$('#pagePin').append(pinMarkup);
I rewrote the Pinterest button code to support the parsing of Pinterest tags after loading AJAX content, similar to FB.XFBML.parse() or gapi.plusone.go(). As a bonus, an alternate JavaScript file in the project supports an HTML5-valid syntax.
Check out the PinterestPlus project at GitHub.
The official way to do this is by setting the "data-pin-build" attribute when loading the script:
<script defer="defer" src="//assets.pinterest.com/js/pinit.js" data-pin-build="parsePins"></script>
Then you can render your buttons dynamically like so:
// render buttons inside a scoped DOM element
window.parsePins(buttonDomElement);
// render the whole page
window.parsePins();
There is also another method on this site which lets you render them in JavaScript without the script tag.
Here is what i did.. A slight modification on #Derrick Grigg to make it work on multiple pinterest buttons on the page after an AJAX reload.
refreshPinterestButton = function () {
var url, media, description, pinJs, href, html, newJS, js;
var pin_url;
var pin_buttons = $('div.pin-it a');
pin_buttons.each(function( index ) {
pin_url = index.attr('href');
url = escape(getUrlVars(pin_URL)["url"]);
media = escape(getUrlVars(pin_URL)["media"]);
description = escape(getUrlVars(pin_URL)["description"]);
href = 'http://pinterest.com/pin/create/button/?url=' + url + '&media=' + media + '&description=' + description;
html = '<img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" />';
index.parent().html(html);
});
//remove and add pinterest js
pinJs = '//assets.pinterest.com/js/pinit.js';
js = $('script[src*="assets.pinterest.com/js/pinit.js"]');
js.remove();
js = document.createElement('script');
js.src = pinJs;
js.type = 'text/javascript';
document.body.appendChild(js);
}
});
function getUrlVars(pin_URL)
{
var vars = [], hash;
var hashes = pin_URL.slice(pin_URL.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
Try reading this post http://dgrigg.com/blog/2012/04/04/dynamic-pinterest-button/ it uses a little javascript to replace the pinterest iframe with a new button and then reloads the pinit.js file. Below is the javascript to do the trick
refreshPinterestButton = function (url, media, description) {
var js, href, html, pinJs;
url = escape(url);
media = escape(media);
description = escape(description);
href = 'http://pinterest.com/pin/create/button/?url=' + url + '&media=' + media + '&description=' + description;
html = '<img border="0" src="http://assets.pinterest.com/images/PinExt.png" title="Pin It" />';
$('div.pin-it').html(html);
//remove and add pinterest js
pinJs = $('script[src*="assets.pinterest.com/js/pinit.js"]');
pinJs.remove();
js = document.createElement('script');
js.src = pinJs.attr('src');
js.type = 'text/javascript';
document.body.appendChild(js);
}
Their pinit.js file, referenced in their "Pin it" button docs, doesn't expose any globals. It runs once and doesn't leave a trace other than the iframe it creates.
You could inject that file again to "parse" new buttons. Their JS looks at all anchor tags when it is run and replaces ones with class="pin-it-button" with their iframe'd button.
this works fine for me: http://www.mediadevelopment.no/projects/pinit/ It picks up all data on click event
I tried to adapt their code to work the same way (drop in, and forget about it), with the addition that you can make a call to Pinterest.init() to have any "new" buttons on the page (eg. ajax'd in, created dynamically, etc.) turned into the proper button.
Project: https://github.com/onassar/JS-Pinterest
Raw: https://raw.github.com/onassar/JS-Pinterest/master/Pinterest.js
As of June 2020, Pinterest updated the pin js code to v2. That's why data-pin-build might not work on
<script defer="defer" src="//assets.pinterest.com/js/pinit.js" data-pin-build="parsePins"></script>
Now it works on pinit_v2.js
<script async defer src="//assets.pinterest.com/js/pinit_v2.js" data-pin-build="parsePins"></script>

Categories

Resources