0

My google chrome extension has a background.js and content script that communicate with port.OnMessage but I have noticed that when I run my extension in Chrome://extension it throws an error because it is not a url and the same happens with a new google tab chrome which has no url. How could I block them?

On the internet I got information that said that they were blocked with

"exclude_matches": [
            "chrome://extensions/"
        ]

however, this doesn't work for the version 3 manifest. Also how could it tell you not to run the extension in a new tab (no url)

this is my manifest v3

"name":"Certified Records Full Certificate",
    "description":"Esta extensión permite grabar la pantalla o hacer capturas de pantalla",
    "version": "1.0",
    "manifest_version":3,    
    "background":{
        "service_worker":"background.js"        
    },  
    "content_scripts": [
        {
          "matches": ["<all_urls>"],
          "js": ["content-script.js"],
          "exclude_matches": [
            "chrome://extensions/"            
        ]
        }],  
    "permissions":["storage","activeTab","scripting","tabs","desktopCapture"],
    "action":{
        "default_popup":"popup.html",
        "default_icon":{
            "16":"/images/logo-16.png",
            "32":"/images/logo-32.png",
            "48": "/images/logo-48.png",
            "128": "/images/logo-128.png"
        }
    },
    "icons":{
        "16":"/images/logo-16.png",
        "32":"/images/logo-32.png",
        "48": "/images/logo-48.png",
        "128": "/images/logo-128.png"
    } }

this is my background.js

chrome.runtime.onConnect.addListener(function (port) {
  port.onMessage.addListener(function(msg){
        if (msg.type === 'SS_UI_REQUEST') {
          requestScreenSharing(port,msg);
        }
  });
});

function requestScreenSharing(port, msg) {  
  const sources = ['window'];
  const tab = port.sender.tab;
  desktopMediaRequestId = chrome.desktopCapture.chooseDesktopMedia(
    sources,
    port.sender.tab,
    streamId => {
      if (streamId) {
        msg.type = 'SS_DIALOG_SUCCESS';
        msg.streamId = streamId;
        msg.text ="sharing";        
      } else {
        msg.type = 'SS_DIALOG_CANCEL';
        msg.text ="cancel";
      }      
      
      var tab = getTabId();
      tab.then((value) => {                                
        const respuesta = chrome.tabs.connect(value.id, {
          name: "respuesta",
        });                
        respuesta.postMessage(msg);                              
      }); 

    }
  );
}

async function getTabId() {
  let queryOptions = { active: true, currentWindow: true };
  let [tab] = await chrome.tabs.query(queryOptions);
  return tab;
}

this is my content-script.js

chrome.runtime.onConnect.addListener(function (port) {
  port.onMessage.addListener(function(msg){
    if (msg.type === 'SS_UI_REQUEST') {
      console.log(msg);      
      var background = chrome.runtime.connect();
      background.postMessage(msg);  
    }        

    if (msg.type === 'SS_DIALOG_SUCCESS') {
      console.log(msg);                 
      startScreenStreamFrom(msg.streamId);      
    }        

    if (msg.type === 'SS_DIALOG_CANCEL') {
      console.log(msg);           
    }
    
    if(msg.type === "SS_UI_TAKESCREENSHOT")
    {
      console.log("tomar screenshot");
      TakeScreenShot();
    }

  });  

});

function startScreenStreamFrom(streamId) {
  console.log("compartiendo pantalla");
  navigator.mediaDevices
    .getUserMedia({
      audio: false,
      video: {
        mandatory: {
          chromeMediaSource: 'desktop',
          chromeMediaSourceId: streamId
        }
      }
    })
    .then(stream => {
        window.stream = stream;         
    });
}



async function TakeScreenShot(){          
  setTimeout(async () => {               
    const screen = window.stream;                                
    const track = screen.getVideoTracks()[0];               
    const imageCapture = new ImageCapture(track);                                                      
    await imageCapture.grabFrame()
    .then(function(bitmap) {           
    track.stop();        
    var canvas = document.createElement('canvas');                
    canvas.width = bitmap.width
    canvas.height = bitmap.height
    const context = canvas.getContext('2d')        
    context.drawImage(bitmap, 0, 0, bitmap.width, bitmap.height)
    const image = canvas.toDataURL()    
    var link = document.createElement('a');
    link.download = 'FullCertificateCaptureScreen.png';
    link.href = image
    link.click();        
    })
    .catch(function(error) {
      track.stop();            
      console.log('grabFrame() error: ', error);
    });           
  }, 1000);    
}

this is the popup script

document.getElementById("btn-share").addEventListener("click", function(){  
  var tab = getTabId();
    tab.then((value) => {                        
      chrome.storage.local.set({'pestaña': value.id});
      const port = chrome.tabs.connect(value.id, {
        name: "conexion",
      });
      port.postMessage({ type: 'SS_UI_REQUEST', text: 'start' }, '*');                                    
    }); //fin de tab.then()       
})//fin de click addEventListener 


document.getElementById("btn-capture").addEventListener("click", async function(){
chrome.storage.local.get('pestaña', function (result) {    
  const port = chrome.tabs.connect(result.pestaña, {
    name: "tomarScreenShot",
  });  
  port.postMessage({ type: 'SS_UI_TAKESCREENSHOT', text: 'takescreenshot' }, '*');                                    
  window.close();
 }); 

});


async function getTabId() {
  let queryOptions = { active: true, currentWindow: true };
  let [tab] = await chrome.tabs.query(queryOptions);
  return tab;
}
  • Extensions don't have access to `chrome://` URLs by default unless you start Chrome with a [special command line switch](/q/19042857), so your content script never runs there and you don't need `exclude_matches`. The problem is in your popup.js or background.js so you should use [devtools to debug it](/a/38913799) yourself or post its code in the question. – wOxxOm Apr 06 '22 at 13:31
  • yes, I know that the extension does not run in chrome://extension. I want to make it so that the user cannot run the extension if they are not on a website. Because being in a new tab without url it seems that the extension will not work, that's why I want to block chrome://extension and new tabs without url. – Alfonso José Apr 06 '22 at 13:51
  • I already edited the question and add the content script and background.js – Alfonso José Apr 06 '22 at 13:54
  • The only solution would be to check the tab's URL in your popup.js and display a message inside the popup saying to use it on a web site. – wOxxOm Apr 06 '22 at 14:18
  • That would be perfect. It's what I was looking for but I think I need a pattern, could you help me? – Alfonso José Apr 06 '22 at 14:24
  • You already have getTabId so in tab.then you can check tab.url and set document.body.textContent accordingly. You can do it on start of the script, not inside the click handler, so the UI is updated automatically. – wOxxOm Apr 06 '22 at 14:29

0 Answers0