chrome.webNavigation.onCompleted在完成之前被解雇了?

时间:2016-08-12 15:20:04

标签: javascript google-chrome-extension firefox-addon opera-extension

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

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我确实得到了正确的号码。

1 个答案:

答案 0 :(得分:1)

正如wOxxOm所暗示的那样,阻止您的代码工作的是您尝试从background script访问DOM。具体来说,代码:

def scan():
    for c in reddit_client.get_comments('chosen_subreddit'):
        if keyword not in c.body.lower(): #check main requirement
            continue
        if c.author == None: #comment deleted
            continue
        if c.author.name == bot_name: #don't bother with comments made by bot
            continue
        answer(c,c.link_id[3:])

def answer(comment, sub_id)
    sub = reddit_client.get_submission(submission_id=sub_id)
    sub.replace_more_comments(limit=None,threshold=0)
    flat_comments = praw.helpers.flatten_tree(sub.comments)
    if len([com for com in flat_comments if com.author != None and com.author.name.lower() == bot_name.lower()]) > 0:
        return False
    #here you can prepare response and do other stuff
    #....
    #....
    comment.reply(prepared_response)
    return True

将无法在后台脚本中运行。如果要执行此操作,则需要加载/执行内容脚本。