Reputation: 877
I am developing a firefox addon by using crossrider which captures url and title. The addon works fine when trying to capture title and url from browser. The addon captures url fine from google search, but it captures the previous title and display it. The same code works fine in chrome. Please refer the code given below:
var capture_data = {
title : "not defined",
desc: "not defined",
url : "not defined",
get_info : function(){
this.url = document.location.href;
this.title = document.title;
console.log("Url: "+this.url+" Title:"+this.title)
}
}
window.onhashchange = function(){
console.log(window.location.hash);
capture_data.get_info();
}
Please give me a solution
Upvotes: 0
Views: 99
Reputation: 37268
If onhaschange is triggering before page title is updated you can try a mutation observer to avoid setTimeout.
You will watch the childNode
of title
element.
So try this:
window.onhashchange = function() {
console.log(window.location.hash);
var title = document.querySelector('title');
var mobs = new window.MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type, mutation);
if (mutation.addedNodes && mutation.addedNodes.length > 0) {
console.log('nodes added');
}
});
});
mobs.observe(title, {
childList: true,
subtree: true
});
}
untested but should get you pretty far, just need watch the console.log
s and you can narrow it down to do just what you need.
Upvotes: 2
Reputation: 3753
I tested the provided code and could reproduce the issue you experienced.
It appears to be a simple matter of the onhashchange event handler being called before the page title is updated. The problem is resolved by introducing a short delay before getting the title, as shown in the following code.
window.onhashchange = function(){
console.log(window.location.hash);
setTimeout(function() {capture_data.get_info();}, 1000);
}
[Disclosure: I am a Crossrider employee]
Upvotes: 1