Avoiding the "urls" format using the onBeforeRequest function

chrome.webRequest.onBeforeRequest.addListener(function(details) {
    if (localStorage.on == '1') {
        return {cancel:true};
    }
}, {urls: ["*://*.domain1.net/*","*://*.domain2.com/*","*://*.domain3.com/*"], types: ["script","xmlhttprequest","other"]}, ["blocking"]);

Is there a way to exclude URLs that match a certain pattern? I want to block all requests except those made to the specified 3 domains. I considered using cancel:true for all requests and allowing the exact content for the 3 domains. Do I need to be concerned about one listener taking precedence over another? How can I modify the code to return the exact content for the specified domains instead of canceling the request?

Answer №1

Here is an example showcasing how to restrict all requests except those directed towards domain1.net and domain2.net:

    chrome.webRequest.onBeforeRequest.addListener(
       function(details) {
         return {cancel: details.url.indexOf(".domain2.net/") == -1 && details.url.indexOf(".domain1.net/") == -1};
       },
    {urls: ["<all_urls>"]},
    ["blocking"]);

Upon reviewing the documentation, it seems there is no straightforward method to negate the URL pattern.

However, Xan proposes a more effective technique for verifying the domain1.net and domain2.net URLs in the response below.

Answer №2

While Paulo Prestes' answer is mostly accurate, it should be noted that "negative" filters are not supported. However, the suggested filter can be easily circumvented.

For example, consider the URL: https://example.com/something?foo=.domain2.net/

Although this URL matches the rule, it is clear that this is not the intended target. Adding an extra parameter can easily bypass the filter without affecting most pages.

Instead, a more robust approach would be to use a set of regular expressions specifically designed to extract the domain:

function validateDomain(url) {
  // Explanation of RegEx:
  // ^                     start of the string
  // http                  exactly "http"
  // s?                    optional "s"
  // :\/\/                 exactly "://"
  // ([^\/]+\.)?           one or more characters not including "/" followed by "."
  // domain\.net\/         exactly "domain1.net/"

  return /^https?:\/\/([^\/]+\.)?domain1\.net\//.test(url) ||
         /^https?:\/\/([^\/]+\.)?domain2\.net\//.test(url) ||
         /^https?:\/\/([^\/]+\.)?domain3\.net\//.test(url) 
}

/* ... */
  return {block: !validateDomain(details.url)};
/* ... */

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize the datepicker function in jQuery version 1.6.3 to select a range of dates

I need help adding a jQuery datepicker to my JSP page for selecting a date range. Below is the current code I am working with. $(function() { $( "#createdAtFrom" ).datepicker({ defaultDate: "+1w", changeMonth: true, ...

Create and store a new data entry in the custom taxonomy of a specific post

I have successfully added an upload image feature to my custom post type taxonomy. The post type is portfolio, and the taxonomy is portfolio-category. The input field for adding the image (which opens the WordPress uploader) is functioning properly. Howev ...

How to position an absolute element beneath a fixed element

My website is experiencing a problem where the fixed header is overlapping an absolute paragraph on this page. Does anyone know how to resolve this issue? ...

Challenge encountered with Promise failing to resolve despite multiple retry attempts

I've been struggling with Promises as a beginner for the past few days. I need to make an API call and check if there is a response. If not, I have to retry calling the API a configurable number of times. I attempted the following code, but I'm u ...

Troubleshooting a shadow mapping problem in three.js involving a ShaderMaterial that alters the positions of vertices

Within my current project, I have implemented a ShaderMaterial to depict terrains. The positions of the vertices are adjusted in the vertex shader based on information from a height map texture: vec4 mvPosition = modelViewMatrix * vec4( position + normal ...

Guidance on incorporating CSS into ES6 template literals within a react framework

I am trying to implement the Material UI stepper in my React application. The step content is set up as a string literal. My goal is to include CSS styling for paragraphs within the step content. Many online resources suggest using \n to add a line ...

Obtain JSX content from a React Component that has been imported

As part of our library documentation efforts, I am looking to convert a React Component function into JSX format. To illustrate, let's consider a rendered Button component and showcase the code used to create it. One approach could be to simply read ...

What could be causing my external JavaScript file to not function properly upon loading my HTML file?

I have organized my code by separating the HTML and JavaScript portions. The JavaScript code is now in its own separate file and I use 'script' tags to reference it in the HTML file. Within the JavaScript code, I have two functions - one creates ...

Emphasize table cells dynamically

Query How can I dynamically highlight a selected td? Codepen Example View Pen here Code Snippet The map consists of a randomly generated 2D array, like this: map = [[1,1,1,1,0], [1,0,0,0,0], [1,0,1,1,1], [1,0,0,0,1], [1,1, ...

Scrolling the y-axis with a fixed height limit to prevent overflow

My current dilemma is a seemingly simple one: <div class="container"> <div class="a"></div> <div class="b"></div> <div class="c"></div> </div>​ Within the container, there are 3 divs: A and B ...

Create a personalized and distinct name following the submission of data into multiple text fields either through Nuxt/Vue or by utilizing pure JavaScript

In my new app, users can register packages and then participate in a ballot session where the package will be assigned to someone else. To make this process smoother, I want each ballot session or box to have a unique Ballot ID attached to it. For example ...

Exploring the nuances of various browsers in JavaScript

I am facing an issue where my JavaScript code functions correctly in Internet Explorer, but not in Firefox or Safari. I have a loop that goes through each element and, depending on the variable inside a text box, triggers an alert message. The code snippet ...

Ways to capture targeted requests

Utilizing NestJS and Angular 2, I have noticed that both frameworks have a similar approach when it comes to working with Interceptors. I am currently looking for the best practice to identify specific requests in order to perform additional tasks. When d ...

Guidelines for implementing a seamless translation effect with CSS3

CSS: .horizon { position: absolute; top: 380px; width: 1800px; height: 50px; background: url(images/road.png) repeat-x; -webkit-animation-name: prop-600; -webkit-animation-duration: 20s; -webkit-animation-iteration-count: i ...

Error: Javascript unable to generate video thumbnail using ffmpeg

I'm having trouble generating a thumbnail from a video file using JavaScript. I keep encountering the error below: ChildProcessError: `/workspace/node_modules/@ffmpeg-installer/linux-x64/ffmpeg -ss 0 -i valid-video-link -f image2 -vframes 1 -vf scale= ...

How can I run JavaScript code written in the Chrome console on standalone Node.js platform

After successfully creating a script that functions when input into the Google Chrome developer console, I now desire to convert it into an executable file. My goal is to open the file and have it log all activity in a separate node.js console window, whil ...

Check that EACH radio button has been either selected or left unselected when the button is clicked

I'm still learning Javascript and currently working on a function triggered by a button click. My goal is to display an alert if NONE of the radio buttons have been selected, regardless of whether they are "Yes" or "No." If ALL radio buttons have been ...

Using array.map() in React does not display elements side by side within a grid container

I'm currently working with React and material-ui in order to achieve my goal of displaying a grid container that is populated by an array from an external JavaScript file. The challenge I am facing is getting the grid to show 3 items per row, as it is ...

Utilizing External Libraries Added Through <script> Tags in React

My goal is to develop a Facebook Instant HTML5 application in React. Following their Quick Start guide, Facebook requires the installation of their SDK using a script tag: <script src="https://connect.facebook.net/en_US/fbinstant.6.3.js"></scrip ...

When using Thunderbird Webextensions, calling .messages.getFull() may result in the Exception 0x80004005 being raised, specifically indicating

This question is a follow-up to a previous question/answer found at: In this scenario, the code attempts to retrieve a list of accounts, select the emailAccountName, get a MessageList object from the specified wantedMailFolderType, and then access a Messa ...