1

I am trying to make a bookmarklet. It should test if the url contains a certain word, if not, it will encode it and add some text to the beginning of the url. So far, I have figured out how to test for the word. The code I am using for that is as follows:

if (document.location.href.indexOf('math') === -1){ 
    alert("Math detected");
}

I want to encode the url like this: If the url it detects is this, http://www.coolmath-games.com/ it should redirect to tunneler.pw/index.php?q=http%3A%2F%2Fwww.coolmath-games.com%2F. Ideally, it wouldn't use regex, but it isn't a big deal if it does.

If it doesn't detect the word, it shouldn't do anything.


EDIT: If anyone was curious, here is the code converted to bookmarklet form.

javascript:void%20function(){-1===document.location.href.indexOf(%22math%22)%26%26alert(%22Math%20detected%22)}();
4
  • You can use encodeURIComponent this Commented Oct 9, 2017 at 17:22
  • Yeah, I tried that and I think I got it to work, but the part I was having real trouble with was adding the text to the beginning of the converted url. Commented Oct 9, 2017 at 17:26
  • Actually i didnt unserstand would you like to encode url and redict with as query string oarama? Commented Oct 9, 2017 at 17:30
  • If math has to be part of the domain, you have to match it in the domain part of the url. like if ^(?:https?://)?([^/?]*?math[^/?]*?)(?=/|$) replace with tunneler.pw/index.php?q=http%3A%2F%2F$1%2F Commented Oct 9, 2017 at 17:37

1 Answer 1

0

Try this:

if (document.location.href.indexOf('blocked') === -1){ 
    document.location.href = "http://tunneler.pw/index.php?q=" + encodeURIComponent(document.location.href);
}

encodeUriComponent will escape the URL, so you will be able to use it in the query string of another URL.

Sign up to request clarification or add additional context in comments.

7 Comments

Could you clarify? What I want to do is, if the url does not contain the word 'blocked,' it should encode the url and add "tunneler.pw/index.php?q=" to the beginning of the url. Thanks.
Ok, I'll update my answer to reflect this. It wasn't clear in the question.
Also, it won't just be for this one "coolmathgames" website, it should work for any. I really appreciate your help!
For some reason, this isn't working as a bookmarklet, even after I convert it. I will have to try it not as a bookmarklet and see what is wrong.
I just tried it in a Javascript shell and got this error: ReferenceError: encodeUriComponent is not defined
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.