Issue opening new tab in multiple functions in Javascript for Chrome Extension

微笑、不失礼 提交于 2019-12-13 08:07:42

问题


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:

  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




回答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

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