I'm trying to build a browser for extension for myself. The idea is that when I click the icon of the plugin, it opens a page. I then want to execute some code after that new page has finished loading but somehow it doesn't work.
var result;
chrome.browserAction.onClicked.addListener(function() {
chrome.history.search(
{ text: "", maxResults: 100}, //object
function(results) { //callback
for(var item in results) {
var currItem = results[item];
if (currItem.url.indexOf("some_domain") > -1) {
result = results[item];
break;
}
}
//Go to website
chrome.tabs.create({
'url': result.url
}, function(tab) {
new_tabId = tab.id;
});
}
);
});
Now here comes the part that fails:
chrome.webNavigation.onCompleted.addListener(function(details) {
// if (check for correct URL here) {
var videos = document.getElementsByTagName("video");
var video = videos[0];
alert(videos.length); <--- always Zero! Why??
video.load();
video.play();
video.addEventListener("ended", function() { ... });
// }
});
They are both in the same background script and I do not have a content script.
The permissions in the manifest are "tabs", "history", "webNavigation"
When I check with the developer console and do:
document.getElementsByTagName("video").length
I do get the correct number.
As implied by wOxxOm, what will prevent your code from working is that you are attempting to access the DOM from a background script. Specifically, the code:
var videos = document.getElementsByTagName("video");
var video = videos[0];
alert(videos.length); <--- always Zero! Why??
video.load();
video.play();
video.addEventListener("ended", function() { ... });
will not function in a background script. If you want to do this you will need to load/execute a content script.