Google Chrome Extension: How to detect «This site can’t be reached»

I develop extension for Google Chrome (something like proxy).

But how can i detect error «This site can’t be reached» (DNS_PROBE_FINISHED_NXDOMAIN).

Load unpacked Chrome extension – how does it know where my index.html file is?

I have a Chrome Extension project, the structure looks like this:

project/
  dist/
    index.html
  manifest.json

When I go More Tools -> Extensions -> Load Unpacked Extensions

I choose the root of the project, and it works! But I can’t figure out how it knows to load dist/index.html? The manifest.json file doesn’t say anything about dist/index.html, so how does Chrome know how to load the extension?

I built this extension a few months ago, and now I can’t figure out how it works lol.

the manifest.json file looks like this verbatim:

{
  "manifest_version": 2,
  "name": "Suman Generator",
  "description": "This extension allows the user to generate test skeletons.",
  "version": "1.223",
  "browser_action": {
    "default_icon": "icon.png"
  },
  "options_page": "options.html",
  "options_ui": {
    "page": "options.html",
    "chrome_style": true
  },
  "devtools_page": "aspects/dev-tools/dist/suman-dev-tools.html",
  "optional_permissions": [
    ""
  ],
  "permissions": [
    "management",
    "activeTab",
    "webNavigation",
    "storage",
    "*://*/",
    "http://*/",
    "https://*/",
    "background",
    "browser",
    "tabs",
    "identity",
    "identity.email",
    "https://www.googleapis.com/",
    "pageAction",
    "notifications",
    "clipboard",
    "clipboardWrite",
    "clipboardRead",
    "unlimitedStorage",
    "webRequest",
    "userinfo",
    "webRequestBlocking",
    {
      "socket": [
        "tcp-connect:*:*"
      ]
    }
  ],
  "web_accessible_resources": [
    "modal-iframe.html"
  ],
  "icons": {
    "16": "icons/icon16.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  },
  "omnibox": {
    "keyword": "suman:chrome"
  },
  "oauth2": {
    "client_id": "5461307462-7geu9374.apps.googleusercontent.com",
    "scopes": [
      "https://www.googleapis.com/auth/userinfo.profile",
      "https://www.googleapis.com/auth/chromewebstore.readonly"
    ]
  },
  "key": "MIIBC57LwMgUdRxfY4I40oAiKy57o3tWF/A1BrTNY0nQIDAQAB",
  "short_name": "Suman Short Name",
  "offline_enabled": true,
  "background": {
    "page": "background.html",
    "persistent": true
  },
  "content_scripts": [],
  "content_security_policy": "script-src 'self' https://plus.google.com 'unsafe-inline' 'http' 'https' 'unsafe-eval' '*'; object-src '*';"
}

webRequest.onBeforeRequest and SendNativeMessage

I am working on a extension which uses an algorithm implemented in native code to determine if a URL is safe or not. If it is deemed unsafe the navigation should not be allowed to load anything.

I am using chrome.webRequest.onBeforeRequest and chrome.runtime.sendNativeMessage.

The problem I am hitting is that SendNativeMessage is async so the response comes to late and the page has already started to load. I have seen alot of post saying javascript is async, you shouldnt block. I get that, but in this case for security reasons i need to block. From what i can tell mozilla allows for async blocking request, but chrome does not.

Anybody help would be appreciated.

error : {code: 400, message: “API key not valid. Please pass a valid API key.”

I’m developing a chrome extension application and so I’ve already created an API key and OAuth2 Client ID, and I’ve been able to get google drive files with no problem, but when I try accessing a spreadsheet I just get this error saying my API key is invalid. I’ve included all the necessary scopes, made sure that Google Drive and Google sheets are enabled, and deleted and recreated my API key, but still get this same error. Please help.

  window.onload = function() {
document.getElementById('pi').addEventListener('click', function() {
  chrome.identity.getAuthToken({interactive: true}, async function(token){

    //setToken(token);
    let init = {
      method: 'GET',
      async: true,
      headers: {
        Authorization: 'Bearer ' + token,
        'Content-Type': 'application/json'
      },
      'contentType': 'json'
    };
    //var theFoundURL = await getUrl2();
    //console.log("THE FOUND URL: " + theFoundURL);
    fetch(
        "https://sheets.googleapis.com/v4/spreadsheets/1b9NsKlhFeCDHXHGekQjhVxRmKfnijRs8Mkx9RFr9DIs/values/Sheet1A1%3AB1?key={MYAPIKEY}",
        init)
        .then((response) => response.json())
        .then(function(data) {
          console.log(data)
          let nowD = "1"; //getDate();
          if(nowD != data[0]){
              console.log("FALSE");
          }

          else console.log("TRUE");
        });




});

  }
  );
}

Javascript^

{

"manifest_version": 2,

"name": "G",
"version": "1.0",



"browser_action":{
"default_icon": "icon.png",
"default_popup": "popup.html"
},

"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",


"permissions": [
    "tabs",
    "storage",
    "activeTab",
    "alarms",
    "identity"
    ],

"oauth2": {
    "client_id": "MYID",

    "scopes": [
        "https://www.googleapis.com/auth/drive.file",
        "https://www.googleapis.com/auth/drive.readonly",
        "https://www.googleapis.com/auth/drive.metadata.readonly",
        "https://www.googleapis.com/auth/drive.metadata",
        "https://www.googleapis.com/auth/drive.appdata",    
        "https://www.googleapis.com/auth/drive",
        "https://www.googleapis.com/auth/spreadsheets",
        "https://www.googleapis.com/auth/spreadsheets.readonly"
    ]
},

"key": "MYKEY"

}

Manifest.json ^

Basic Chrome Extension programming: unable to dynamically block websites

I’m trying to write a simple chrome extension that blocks twitter when I click on it.

Here’s my background.js:

var enabled = true;
const global_blocked_urls = ["https://*.chess.com/*"];



chrome.webRequest.onBeforeRequest.addListener(
    (details) => {
        console.log(global_blocked_urls); //prints as expected 
        console.log("blocking:", details.url);
        return {
            cancel: enabled
        };
    }, {
        "urls": global_blocked_urls
    }, ["blocking"]
);

chrome.runtime.onMessage.addListener(block_twitter);

function block_twitter(msg) {


        var twitter_regex = "https://*.twitter.com/*";
        global_blocked_urls.push(twitter_regex);
        console.log(global_blocked_urls);

    console.log(msg);
}

I’m holding a list of links that I don’t want to visit, inside a global list.

The problem: Say the block_twitter listener is triggered first, and then I visit a new webpage – so the onBeforeRequest listener is triggered next. When I print out the global list inside callback to chrome.webRequest.onBeforeRequest.addListener, it prints out what I expect it to print out.

But: it still allows me to visit twitter, despite the regex twitter url being the in the global list.

How do I debug/fix this?

chrome.contextMenus.create with dynamic items

I want to build a chrome extension that has a menu with some items based on what you click on.

i use chrome.runtime.onConnectExternal to pass the date, everything works fine in here. but as the messaging between extension and site is done async some time the events come after the menu gets shown. and it dose not update after that.
the end result is that some times you see the menu based on the old item that was right clicked.

Is there a way to refresh the menu while open. or a way to comunicate between site and extension in a sync way?

Here is a example showing menu not updating:

const test = chrome.contextMenus.create({
    'title': `menu 0`,
    "contexts": ['all'],
});

let index = 0;

setInterval(() => {
    chrome.contextMenus.update(test, {title: 'menu ' + index++})
}, 1000);

send message to content script from background with delay ? chrome extension

I want to senMessage from background to content script , however the I want the background to send the message after a specific time , here is my code :

background :

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
    if (msg.id == "openUrl") {
        var tabId = sender.tab.id;
        var url = msg.url;
        openUrl(tabId, url);
    } else if (msg.id == "background") {
        setTimeout(function() {
            chrome.tabs.query({
                active : true,
                currentWindow : true
            }, function(tabs) {
                chrome.tabs.sendMessage(tabs[0].id, {}, null);
            });
        }, 5000);
    }
});

I am receiving the bellow error :

**Error in response to tabs.query: TypeError: Cannot read property 'id' of undefined**

I am not sure , why the chrome api can get the selected tab ?

You can download the source file here :

https://drive.google.com/open?id=1_Hkedx8ldAeRWiFKTj4YEv_bXFUt-3CY

Thank you .

Permission error in executeScript

I am trying to inject some js file while tab open.So, on tab open i execute

chrome.tabs.onCreated.addListener(function callback(tab, info) {   
 chrome.tabs.executeScript(tab.id, {
                         file: "executeScript.js"
      });
});

but some time it works ,some time i am getting

Cannot access contents of url “https://www.google.com/_/chrome/newtab?rlz=1C1CHZL_enIN708IN708&ie=UTF-8“. Extension manifest must request permission to access this host.
error.
i have added * ://*/ * , in manifest file permission but no luck.

Chrome Extension: require.js is not loading modules

I’m trying to load the sentiment module, using require.js in my content.js as explained in this doc:

require(['./require', '../node_modules/sentiment'], function (require) {
    //sentiment is now loaded.
    var sentiment = require('../node_modules/sentiment');
    if (sentiment) { 
        console.log('sentiment module loaded'); 
    }
});

There are no console errors, so I’m not entirely sure why nothing is being printed to the console or how to fix this issue.

Store persistent data without a web server for Chrome Extension

Is there any way to store persistent data for Chrome Extensions without using a web server?

Is Chrome storage persistent? https://developer.chrome.com/apps/storage

I want to avoid the costs of a server, but I also don’t think localStorage is good enough because the user can delete it.

In fact, the only persistent data I need to store is the accounts that have logged into the extension on the device itself, so that info might be stored by Google’s servers already?