问题
I am working on a Chrome extension, but for some reason I am able to create a new tab only in a single function and not in multiple functions.
Code-
function editorial() {
chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
var tab_url=tabs[0].url;
var new_url=tab_url.slice(11);
chrome.tabs.create({ url:"http://www.discuss." + new_url});
});
}
document.addEventListener('DOMContentLoaded', function () {
var btn = document.getElementById('viewEditorial');
if (btn) {
btn.addEventListener('click', editorial);
}
});
function friends()
{
var frnd_name=document.getElementById('frnd1').value;
alert(frnd_name+"rocks");
/*chrome.tabs.query({currentWindow: true, active: true}, function(tabs){
var tab_url=tabs[0].url;
var new_url=tab_url.slice(11);
chrome.tabs.create({ url:"http://www.discuss." + new_url});*/
}
document.addEventListener('DOMContentLoaded', function () {
var btn2 = document.getElementById('viewFriends');
if (btn2) {
btn2.addEventListener('click', friends);
}
});
I want to be able to use the frnd_name to open a url in a new tab in the function friends().
If the commented part is not used then it is working fine and the alert message is also coming but if the commented part is used then for some reason, it does not work.
Any ideas as to what the bug/problem is?
回答1:
I think it's because chrome.tabs cannot be used in content scripts.
You should do this instead:
- Send a message to your background page using chrome.runtime.sendMessage
- In your background page, use chrome.runtime.onMessage to catch the message
- Finally use chrome.tabs.create to create a new tab.
Hope this helps
回答2:
Well, the problem was due to a missing '}' that was not there. I wasted a lot of time over this and ultimately the bug was such a simple one. Now, I have learnt a lesson, always check ur code twice for proper braces.
来源:https://stackoverflow.com/questions/25584927/issue-opening-new-tab-in-multiple-functions-in-javascript-for-chrome-extension