问题
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