I use the following code to automatically grab/set the latest page title every 30 seconds:
<script type="text/javascript">
setInterval(function() {
var data = "http://mysite.com/mypage.php";
$.get(document.location.toString()).then(function (data){
//find and set the title of the page
document.title = data.match(/<title>(.+)<\/title>/)[1];
});
}, 30000);
</script>
It works great, except for titles which include an ampersand. These load normally, and then after 30 seconds are replaced with:
&
So if the page title is:
Fun & Games
After 30 seconds, it becomes:
Fun & Games
Thanks
Instead of using a regex to extract the title, try asking the DOM what the title of the returned page is. The problem is, in your file, it's &, but once it's parsed it becomes &.
$.get(document.location.toString()).then(function (data){
//find and set the title of the page
document.title = $(data).filter('title').text();
});
I'm assuming your raw HTML source has something like <title>Fun & Games</title>, which is what it should have to be valid.
This is fine when it's processed by the browser, as it will understand the & as an ampersand.
However, in the context of JavaScript, setting document.title is a plain string, not one parsed by HTML. Therefore, the & is not interpreted, and is left as is.
Personally, I have a function called unHTMLref in my "toolbox", defined as so:
window.unHTMLref = function(str) {
if( !str) return str;
var d = document.getElementById('__unHTMLref');
if( !d) {
d = document.createElement('div');
d.id = '__unHTMLref';
d.style.display = "none";
document.body.appendChild(d);
}
d.innerHTML = str.replace(/</g,'<');
return d.firstChild.nodeValue;
};
This will decode all HTML entities, and return the parsed string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With