-1

due to the my lack of knowledges in javascript, i m here to please you to explain me why this line of code is not working properly, as it should do.

Firstly let me explain what I am trying to do and after that i will let you see my code. So, I'm using this guy script to check if adblock is active or not. https://stackoverflow.com/a/24111206

I changed adblock variable with adblock = "http://www. example1. tld" and adblock = "http://www. example2. tld".

I need to write adblock variable within href attribute of the < a > html tag. But till now I didn't find out how. The line of code that is not working is the next one:

 <script>document.write('<a href="<script> document.write(adblock)</script>"' + 'class="button-download popup">')</script>

Can somebody explain me what to do in this situation and why my code is not working properly?

Community
  • 1
  • 1
  • 2
    Because when parser meets a literal end tag for `script`, it stops parsing. You've to obfuscate the end tag, for example `document.write('..."'...)` – Teemu Mar 19 '17 at 17:12
  • don't use `document.write`: http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice – Claies Mar 19 '17 at 17:13
  • 2
    Just Google `.setAttribute()` – zer00ne Mar 19 '17 at 17:13
  • `adblock`, taken from that user's example, is just a boolean variable. What are you trying to do with it? – Blender Mar 19 '17 at 17:20
  • This worked well http://stackoverflow.com/a/40280454/295783 – mplungjan Mar 19 '17 at 17:27
  • @mplungjan, sorry but that didn't helped me too much, thank you anyway! – Simple Beginer Mar 19 '17 at 21:07
  • mplungjan, sorry but that didn't helped me too much, thank you anyway! | zer00ne thanks for answer, i will check that out to improve my js bag of knowledges. | claies, thanks, i will keep that in my mind. | teemu, thanks for explication. – Simple Beginer Mar 19 '17 at 21:09

1 Answers1

0

Your code doesn't work properly because </script> denotes the end of a script, regardless of where it is in your script (in your case, inside of a string).

But even if you fix that, your code has no chance of working, since you can't put <script> tags into the href attribute of an anchor tag and expect it to run. If you want to create a link with a URL set by a variable, you can do that with document.createElement():

<script>
var a = document.createElement('a');
a.href = adblock;
a.className = 'button-download popup';
a.textContent = 'foo';

document.querySelector('#somewhere > foo').appendChild(a);
</script>

Using document.write() is usually bad practice. If you insist on using it, you can modify your code like this:

document.write('<a href="' + adblock + '" class="button-download popup">foo</a>');
Blender
  • 257,973
  • 46
  • 399
  • 459
  • even is or not a bad practice this is all i need for now. I hope that my javascript (or web development languages) knowledges will improve by time! Thanks a lot! – Simple Beginer Mar 19 '17 at 21:06