0

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?

0

2 Answers 2

0

I think it's because chrome.tabs cannot be used in content scripts.

You should do this instead:

  1. Send a message to your background page using chrome.runtime.sendMessage
  2. In your background page, use chrome.runtime.onMessage to catch the message
  3. Finally use chrome.tabs.create to create a new tab.

Hope this helps

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

You can use a linting tool, such as JSLint or JSHint to validate your code. It will save you a lot of time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.