chrome.webNavigation.onCompleted 未完成就解雇了?

chrome.webNavigation.onCompleted fired before completion?

我正在尝试为自己构建一个用于扩展的浏览器。这个想法是,当我点击插件的图标时,它会打开一个页面。然后我想在新页面加载完成后执行一些代码,但不知何故它不起作用。

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;
            });
        }
    );
});

下面是失败的部分:

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() { ... });
   // }
});

它们都在同一个后台脚本中,我没有内容脚本。 清单中的权限是 "tabs", "history", "webNavigation"

当我检查开发人员控制台并执行以下操作时: document.getElementsByTagName("video").length 我确实得到了正确的数字。

正如 wOxxOm, what will prevent your code from working is that you are attempting to access the DOM from a background script 所暗示的那样。具体代码:

var videos = document.getElementsByTagName("video");
var video = videos[0];
alert(videos.length); <--- always Zero! Why??
video.load();
video.play();

video.addEventListener("ended", function() { ... });

将无法在后台脚本中运行。如果您想这样做,您需要 load/execute 内容脚本。