简体   繁体   中英

Switch URL in chrome extension

Preface: I'm a beginner to this stuff.

I'm trying to make an extension that replaces the current tab url with a predefined url. So far I have the following:

    chrome.tabs.getSelected(null, function(tab){
      chrome.tabs.update(tabs.id, {url: "https://www.wikipedia.org/"});
    });

The chrome app developer tool tells me that "tabs is not defined" but I have "tabs" in my manifest permissions. Manifest:

"permissions": [
    "tabs",
    "declarativeContent",
    "https://www.wikipedia.org/"
],

"background": {
    "scripts": ["background.js"],
    "persistent": false
},

"browser_action": {
    "default_icon": "icon-19.png",
    "default_title": "Simple-Switch"
}

Permissions don't declare variables that you can use (as if there were a " var tabs "); they define what functions you are allowed to use (in this case, that you can call functions in chrome.tabs ).

Your problem is that your callback takes an argument of tab , but you use the variable tabs . Hence "tabs is not defined". So the simplest fix would be function(tabs) . But you should also use tabs.query instead of the deprecated tabs.getSelected :

chrome.tabs.query({active:true,currentWindow:true}, function(tabs){
    chrome.tabs.update(tabs[0].id, {url: "https://www.wikipedia.org/"});
});

You can also change the tabs permission to activeTab .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM