crzyonez777 crzyonez777 - 4 months ago 14
Javascript Question

Chrome extension - "webNavigation.onComitted" event is fired twice

I'm developing a chrome extension now.

I came across this problem that "webNavigation.onComitted" event is fired twice on facebook.com when I access facebook.

This is the code I have now, but it prints "Facebook" twice in console.

// while logging in facebook.com, it prints "facebook" in console.
chrome.webNavigation.onCommitted.addListener(function(e) {

console.log("Facebook");

}, {url: [{urlPrefix : 'https://www.facebook.com/'}]})


On the other hand, this code works ok.
When I access youtube.com, it prints "youtube" just once in console as I expect.

// on accessing youtube.com, it prints "youtube" in console.
chrome.webNavigation.onCommitted.addListener(function(e) {

console.log("youtube");

}, {url: [{urlPrefix : 'http://www.youtube.com/'}]})


Anyway, I want it load only once when accessing facebook.com.

How can I make it work??

If anyone knows how to fix this problem,please help me out!!

Thanks in advance!!

What I tried

http://developer.chrome.com/extensions/webNavigation.html#events

I tried all other event types such as "onBeforeNavigate", "onCompleted".
But it doesn't solve my problem.

Useful related post on stackoverflow

Chrome extension, javascript: Why is this firing twice?

This page is similar to my problem but, this page is talking about "tabs.onUpdated" event.

since "tabs.onUpdated" event doesn't provide event filter, I prefer using "webNavigation" API.

Answer

From http://developer.chrome.com/extensions/webNavigation.html#event-onCommitted:

frameId ( integer )

0 indicates the navigation happens in the tab content window; a positive value indicates navigation in a subframe. Frame IDs are unique within a tab.

If you add console.log(e) inside your event handler, you'll see that the first event has frameId = 0, while the second event has a positive number, which means it belongs to an iframe. If you are only interested in main window navigation, just add a check for e.frameId === 0 at the beginning of your event handler.