Interrupting JavaScript execution upon the setting of a cookie

Can you disrupt JavaScript execution in web browser developer tools every time a cookie is set (without explicitly setting JS breakpoints)?

document.cookie = '...';

Answer №1

By inserting the following code snippet at the beginning of the HTML → head section, everything functions correctly:

<script type="text/javascript">
    function debugAccess(obj, prop, debugGet){
        var origValue = obj[prop];
        Object.defineProperty(obj, prop, {
            get: function () {
                if ( debugGet )
                    debugger;
                return origValue;
            },
            set: function(val) {
                debugger;
                return origValue = val;
            }
        });
    };
    debugAccess(document, 'cookie');
</script>

To learn more about this technique, visit this page on Angular University's blog.

Answer №2

To make this code work, execute it in a browser console:

originalDescriptor = Object.getOwnPropertyDescriptor(Document.prototype, 'cookie');
Object.defineProperty(document, 'cookie', {
  get() {
    return originalDescriptor.get.call(this);
  },
  set(value) {
    debugger;
    return originalDescriptor.set.call(this, value);
  },
  enumerable: true,
  configurable: true
});

Answer №3

Enhancing the approach of overriding the entire HTMLDocument.prototype cookie property involves utilizing Reflect and Proxy. By adopting this method, rather than needing to create an override for every aspect of the cookie property, you only need to focus on the specific method (e.g., when the cookie is being set).

Reflect.setPrototypeOf(document, new Proxy(Reflect.getPrototypeOf(document), {
  set(target, key, value, thisArg) {
    if (key === 'cookie') {
      // execution path when document.cookie receives a new value
      debugger;
    }

    // proceed to the original object assignment
    return Reflect.set(...arguments)
  }
}));

Answer №4

If you're using Chrome dev-tools, simply right-click on a cookie within the application cookies section and choose 'show request with this cookie'

Although it's not considered interception, it can be useful in pinpointing the origin of a specific cookie.

Answer №5

One way to approach this is by incorporating it into an If statement.

if(document.cookie.indexOf('...') >= 0){
  debugger;
}

Keep in mind that when using Firefox, you will need to have your console open, unlike Chrome where this is not necessary.

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

Node.js is throwing GitHub API 401 Bad Credentials error, whereas curl is not encountering the

I am attempting to authenticate on Enterprise GitHub using @octokit/rest. When I execute the following Curl command, I receive a list of API URLs: curl -u "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80edf9c0e5ede1e9ecaee3e ...

Accessing html form elements using jQuery

I'm having trouble extracting a form using jQuery and haven't been able to find a solution. I've tried several examples, but none of them display the form tags along with their attributes. Here is a sample fiddle that I've created: Sam ...

Mobile devices experiencing issues in loading Javascript scripts

Let me start by sharing my JS code: function getTimeRemaining(endTimeInput) { var endTime = new Date(endTimeInput); var currentTime = new Date(); var t = endTime - currentTime; var seconds = Math.floor((t / 1000) % 60); var minutes = Math.floor((t / 100 ...

Error message from BitBucket pipeline indicates that the npm command was not found

Upon deploying code to my server via the Bit Bucket scp pipeline, I encountered an issue with another pipeline meant to install node modules and start the node server. The pipeline returned a failed status and displayed the following error: ./server-run.s ...

Selecting dynamic attributes in VueJS - clearing out previous selections

The data attributes are pulled from an API and the names of the attributes are dynamic. However, for the sake of simplicity, I have included an example with an object containing Colour and Size. My main goal was to map the data to an object named selectedA ...

PHP: How to create a custom function to convert JSON data to HTML-encoded text

I am faced with a challenge involving an array containing values from a database, some of which include HTML tags. My goal is to output this array in JSON format, so I am utilizing json_encode for that purpose. However, I am encountering an issue when tr ...

How to check off a checkbox using a jQuery function

I have a listbox displayed in my view. This listbox is using a template Listbox <div id="UsersLoad" style="width: 50%"> @Html.EditorFor(i => i.Users, "UsersForEdit") </div> UserForEdit Template (Code snippet) @model string[] @{ ...

What is the best practice for integrating Angular controllers into an ASP.NET MVC application?

When developing an application in ASP.NET MVC and Angular, it's important to carefully consider where to store Angular scripts. Typically, the main application files containing Angular modules are placed inside the Scripts directory and referenced in ...

Troubleshooting: jQuery unable to retrieve input value on initial page load

Has anyone experienced an issue with getting input value using jQuery? It seems to only work on the second instance when the button is pressed, after going back to the page: Here's the HTML code: <input type="text" class="form-control email_inpu ...

ng-repeat refreshes after compilation

I have a collection of upcoming events retrieved through a JSON request to my server. These events are displayed using ng-repeat in my application. I am looking to add functionality where users can like or unlike an event by clicking on a button. <a ng ...

Define a new type in Typescript that is equal to another type, but with the added flexibility of having optional

I have 2 categories: category Main = { x: boolean; y: number; z: string } category MainOptions = { x?: boolean; y?: number; z?: string; } In this scenario, MainOptions is designed to include some, none, or all of the attributes that belong to ...

Switch out "FOR" in order to sum up every value within an array

Utilizing Javascript, I have an array defined as follows: counts: [ { id: 1, value: 0 }, { id: 2, value: 10 }, { id: 3, value: 5 }, { id: 4, value: 3 } ] I aim to calculate a variable named total that holds the sum of all valu ...

Angular JS is encountering an issue where the promise object is failing to render correctly

I'm currently learning Angular and I have a question about fetching custom errors from a promise object in Angular JS. I can't seem to display the custom error message on my HTML page. What am I missing? Below is my HTML file - <!DOCTYPE htm ...

Guide to clicking on elements with selenium framework

Struggling to scrape a web page from the bookmyshow site using selenium. Encounter two popups upon loading the page, trying to click the necessary buttons to close them. Facing issues locating these elements despite using sleep() to ensure complete page lo ...

The instance is referencing "underscore" during render, but it is not defined as a property or method

I have experience as a skilled react developer, but I've taken over a vue.js project from another developer and managed it for quite some time. Regrettably, I haven't put in the effort to learn vue properly. When using lodash, I encountered an u ...

Guide to changing the checkbox value using JavaScript

Describing the Parent Element: <span style="background: yellow; padding: 50px;" onClick="setCheckBox()"> <span> </span> <input type="checkbox" name="f01" value="100"> </span> ...

The link appears to be broken when trying to access the notFound component in Next.js version 13

In my Next.js 13.4 app directory, I added a not-found.tsx component that functions correctly when entering the wrong route: import Link from 'next/link' function NotFound() { return ( <section> 404, page not found ...

React element failing to appear on webpage

I'm having trouble loading the snippetInfo.js file in the HTML, and I can't seem to figure out why. I've searched online extensively for solutions, but none of them have worked for me. Whenever I try adding type='text/javascript' t ...

Modules controllers angular.js namespacing

In my application directory, I have the following structure: scripts/ modules/ module1/ controllers/ MainController.js module2/ controllers/ MainController.js main.js I am looking to organize the controll ...

The padding of the iFrame does not match the padding of the source

After creating a compact javascript Rich Text Editor, I noticed a discrepancy in the padding of certain elements when I view it within an iframe. This issue is apparent in the image directly from the source: However, when I embed it in an iframe using the ...