Elle
Elle

Reputation: 445

Can I make tell some Javascript code to NOT run, if given text appears in the URL?

(I'm using Greasekit, so I'm working in Javascript)

Can Javascript detect the URL of the currently loaded page?

I have some lines of code but I want to NOT run if VeryHeavy appears in the current URL.

Is this even possible, programmatically?

Example

An example of the current URL would be:

https://www.example.co.uk/wine/newsletter?ie=UTF8&page=35&tab=UK_VeryHeavy

= I want the script to not run

When the URL is

https://www.example.co.uk/wine/newsletter?ie=UTF8&page=35

= I want the rest of the code to run. (In other words, do nothing)

Upvotes: 2

Views: 119

Answers (4)

BrianH
BrianH

Reputation: 2133

The Javascript Window Location Object contains the information you seek.

href = the entire URL: http://www.example.com:8080/search?q=devmo#test

Example:

var url = window.location.href;
alert( url );

You may then use Regex or the indexOf() method to test if the URL string contains something you would like. If you are doing a case-insensitive test it's probably best to use regex, as noted in ethagnawl's answer, as per this thread: fastest-way-to-check-a-string-contain-another-substring-in-javascript

Upvotes: 0

pdoherty926
pdoherty926

Reputation: 10379

if (!(/VeryHeavy/.test(window.location.search))) {
    ...
}

Upvotes: 5

TheMaskedCucumber
TheMaskedCucumber

Reputation: 2029

Sure you can.

Get the page URL in JavaScript with document.URL.

Upvotes: -1

howderek
howderek

Reputation: 2244

Use window.location.href.contains("VeryHeavy")

Just put that inside of an if statement.

Example

if (window.location.href.contains("VeryHeavy")) {
    //do stuff
}

Upvotes: 0

Related Questions