Chrome inject script inconsistency issue

那年仲夏 提交于 2019-12-20 05:11:23

问题


Below function I did was to redirect user to a login page, and then inject a js to login the user. The code below worked well but not consistent, I hardly can debug it because the flow contain refresh of the whole page.

in my setLogin.js I try to debug with alert() wrap within $(function(){}); I found that sometime it run sometime it doesn't. So I suspect the script sometime got injected sometime not, but why is it like so?

chrome.tabs.update(null, {
    url: 'https://example.com/index.php?act=Login'
}, function () {

    chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
        if (changeInfo.status == 'complete') {
            chrome.tabs.executeScript(null, {
                file: "jquery.js"
            }, function () {

                chrome.tabs.executeScript(null, {
                    code: 'var passedData = {username:"' + username + '",pass:"' + pass+'"}'
                }, function () {
                    chrome.tabs.executeScript(null, {
                        file: "setLogin.js"
                    }, function () {
                        window.close(); //close my popup

                    });
                });
            });

        }
    });
});

回答1:


By default scripts are injected at document_idle which doesn't work consistently with jQuery, probably because it's big or uses some asynchronous initialization.

Solution: explicitly specify that the injected scripts should run immediately.

chrome.tabs.executeScript({file: "jquery.js", runAt: "document_start"}, function(result) {
});


来源:https://stackoverflow.com/questions/32752868/chrome-inject-script-inconsistency-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!