简体   繁体   中英

chrome.tabs.create not working

Because my content script cannot use all the chrome API tools, I am sending a message from my content script to my background script. When received, the background script is supposed to open a new tab containing an html file I had made.

This is sending the message from the content script...

chrome.runtime.sendMessage({permission: true}, function(response) {
        console.log(response.access);
});

This is the code to receive the message in my background script...

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.permission == true) {
        chrome.tabs.create({'url': chrome.extension.getURL('./src/permission.html')}, function(tab) {
            sendResponse({access: "yes"});
        });  
    }
});

The message is received, I have already tested that. But when I add the following code...

chrome.tabs.create({'url': chrome.extension.getURL('./src/permission.html')}, function(tab) {
...etc

I get an error saying response not received. Meaning something must have broke inside my chrome.tabs.create . Why is it breaking?

The permission.html path is relative to the background script.

What I want is for a new tab to be created when the message is received.

I'm not sure if this has any affect, but the content scripts and the background scripts communicate asyncronously so for you to use the sendResponse callback, you'll need to return true; at the end of your onMessage anonymous function.

Chrome onMessage return true

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.permission == true) {
        chrome.tabs.create({'url': chrome.extension.getURL('./src/permission.html')}, function(tab) {
            sendResponse({access: "yes"});
        });  
    }
    return true; //to tell the content script to look out for sendResponse
});

Again, I'm not sure if this will solve your problem, but regardless, your response using sendResponse will not work without returning true at the end of the listener

Also, BTW, chome.extension.getURL() does not need a dot-slash so chrome.extension.getURL('src/permission.html') should be enough.

Have you tried just running

chrome.tabs.create({'url': chrome.extension.getURL('src/permission.html')});

(with or without the dot-slash) to see if the tab opens up?

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