问题
I'm trying to make an auto-login button extension for chrome. My code is the following:
options.html:
function gotoAdmin(){
chrome.tabs.create({'url': "http://www."+currentTabDomain+"/admin"}, function(tabId,changeInfo,tab) {
chrome.tabs.executeScript(null, {file: "login.js"});
});
}
...
<img src="admin.png" onClick="gotoAdmin()">
login.js:
$(document).ready(function(){
$('input[name=username]').val('foo');
$('input[name=password]').val('bar');
$('#form').submit();
});
manifest.json:
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["jquery-1.7.2.min.js"],
"run_at": "document_start"
}
],
"background": {
"scripts": ["background.js"]
}
My problem is that when I open the options tab via the developer console and start gotoAdmin(), the jQuery events go just fine and the auto-login works, but when I click the image without having the developer console open, it will not do anything at all (not even open an alert) from login.js.
回答1:
I know, I am joining the party too late, but -just in case someone lands on this question while looking for an answer to a similar problem (like I did)- here is the solution I used:
First, things first:
The problem is that as soon as the new tab is opened, the popup window closes, which causes any JS executing in it to stop as well. So, since the chrome.tabs.create(<specs>, <callback>)
was in the popup window, the callback function is never executed.
The solution:
The solution is to have a background page (or better yet an event page) handle the tab creation process for you. Then, you'll have to initiate the process, by notifying the background/event page.
Step 1:
In the popup, use
// Add whatever arguments you need to pass, in <msg>
chrome.runtime.sendMessage(msg);
Step 2:
Have the background/event page receive the message and act:
// a. Listen for a message, adding a listener.
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
// I got the message, let's parse it.
...
// b. Act upon it, creating the tab etc.
chrome.tabs.create(<specs>, <callback>);
...
});
Take, also, a look at the docs for more info regarding Message Passing.
回答2:
You have to pass the tab.id
instead of null
to the executeScript function and chrome.tabs.create
passes only tab
argument to the callback function, no tabId,changeInfo,tab
:
chrome.tabs.create({'url': "http://www."+currentTabDomain+"/admin"}, function(tab) {
chrome.tabs.executeScript(tab.id, {file: "login.js"});
});
来源:https://stackoverflow.com/questions/10290160/chrome-tabs-executescript-only-fires-when-the-developer-console-is-open