I have a setup to display something when it detects adblock, and it's displaying code instead of working. I am not that experienced in Javascript to know why.
Okay, in my index file I have
<script type="text/javascript" src="inls/advertisement.js"></script>
Now in advertisement.js I have
document.write('<div id="tester">an advertisement</div>');
And now I have the following in my index after that:
<script type="text/javascript">
if (document.getElementById("tester") != undefined)
{
document.write('<center><script type="text/javascript"><!--google_ad_client = "ca-pub-3846434391631935";/* talknow */google_ad_slot = "6591659297";google_ad_width = 728; google_ad_height = 90; //--> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script></center>');
} else {
document.write('<p class="no">We\'ve detected that you\'re using <strong>AdBlock Plus</strong> or some other adblocking software. Please be aware that this is only contributing to the demise of the site. We need money to operate the site, and almost all of that comes from our online advertising. Its not nice to steal.<!-- end .content --></p>');
}
</script>
but where that code is, it displays as this:
Can anyone help?
I took a look at your actual website's source code. It's different to what you posted:
<script type="text/rocketscript">
if (document.getElementById("tester") != undefined)
{
document.write('<center><script type="text/javascript"><!--google_ad_client = "ca-pub-3846434391631935";/* talknow */google_ad_slot = "6591659297";google_ad_width = 728; google_ad_height = 90; //--> <script src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script></center>'); } else {
document.write('<p class="no">We\'ve detected that you\'re using <strong>AdBlock Plus</strong> or some other adblocking software. Please be aware that this is only contributing to the demise of the site. We need money to operate the site, and almost all of that comes from our online advertising. Its not nice to steal.<!-- end .content --></p>'); }
</script>
Based on Why is wordpress placing "text/rocketscript" instead of "text/javascript" when using wp_register_script()? it seems like you need to change your <script> tag to:
<script data-cfasync="false" type="text/javascript>
Also, document.write is considered "bad practice"; you should probably use DOM manipulation instead, i.e. something like:
var adblock = document.createElement('p');
adblock.className = 'no';
adblock.innerHTML = 'Some text here';
var content = document.getElementById('content');
content.insertBefore(adblock, content.firstChild);
Related
I know this has been asked a lot on here, but all the answers work only with jQuery and I need a solution without it.
So after I do something, my Servlet leads me to a JSP page. My JS function should populate a drop down list when the page is loaded. It only works properly when the page is refreshed tho.
As I understand this is happening because I want to populate, using innerHTML and the JS function gets called faster then my HTML page.
I also get this error in my Browser:
Uncaught TypeError: Cannot read property 'innerHTML' of null
at XMLHttpRequest.xmlHttpRequest.onreadystatechange
I had a soulution for debugging but I can't leave it in there. What I did was, every time I opened that page I automatically refreshed the whole page. But my browser asked me every time if I wanted to do this. So that is not a solution that's pretty to say the least.
Is there something I could do to prevent this?
Edit:
document.addEventListener("DOMContentLoaded", pupulateDropDown);
function pupulateDropDown() {
var servletURL = "./KategorienHolen"
let xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.onreadystatechange = function () {
if (xmlHttpRequest.readyState === 4 && xmlHttpRequest.status === 200) {
console.log(xmlHttpRequest.responseText);
let katGetter = JSON.parse(xmlHttpRequest.responseText);
JSON.stringify(katGetter);
var i;
for(i = 0; i <= katGetter.length -1; i++){
console.log(katGetter[i].id);
console.log(katGetter[i].kategorie);
console.log(katGetter[i].oberkategorie);
if (katGetter[i].oberkategorie === "B") {
document.getElementById("BKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie === "S") {
document.getElementById("SKat").innerHTML += "" + katGetter[i].kategorie + "</br>";
} else if (katGetter[i].oberkategorie ==="A") {
document.getElementById("ACat").innerHTML += "" + katGetter[i].kategorie + "</br>";
}
// document.getElementsByClassName("innerDiv").innerHTML = "" + katGetter.kategorie + "";
// document.getElementById("test123").innerHTML = "" + katGetter.kategorie + "";
}
}
};
xmlHttpRequest.open("GET", servletURL, true);
xmlHttpRequest.send();
}
It can depend on how + when you're executing the code.
<html>
<head>
<title>In Head Not Working</title>
<!-- WILL NOT WORK -->
<!--<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>-->
</head>
<body>
<p>Replace This</p>
<!-- Will work because the page has finished loading and this is the last thing to load on the page so it can find other elements -->
<script>
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
</script>
</body>
</html>
Additionally you could add an Event handler so when the window is fully loaded, you can then find the DOM element.
<html>
<head>
<title>In Head Working</title>
<script>
window.addEventListener('load', function () {
const p = document.querySelector('p');
p.innerHTML = 'Replaced!';
});
</script>
</head>
<body>
<p>Replace This</p>
</body>
</html>
Define your function and add an onload event to body:
<body onload="pupulateDropDown()">
<!-- ... -->
</body>
Script needs to be loaded again, I tried many options but <iframe/> works better in my case. You may try to npm import for library related to your script or you can use the following code.
<iframe
srcDoc={`
<!doctype html>
<html>
<head>
<style>[Style (If you want to)]</style>
</head>
<body>
<div>
[Your data]
<script type="text/javascript" src="[Script source]"></script>
</div>
</body>
</html>
`}
/>
Inside srcDoc, it's similar to normal HTML code.
You can load data by using ${[Your Data]} inside srcDoc.
It should work :
document.addEventListener("DOMContentLoaded", function(){
//....
});
You should be using the DOMContentLoaded event to run your code only when the document has been completely loaded and all elements have been parsed.
window.addEventListener("DOMContentLoaded", function(){
//your code here
});
Alternatively, place your script tag right before the ending body tag.
<body>
<!--body content...-->
<script>
//your code here
</script>
</body>
Good evening!
I had a working functionality on a sharepoint document library. It's purpose was to copy the name of a file to the title column.
It was working for a long time but after an update to the sharepoint platform it stopped working and i can't figure out why.
The code:
<input type="button" onclick="updateTitleFromName()" value="Update Title from Name" />
<script type="text/javascript" src="/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="/Scripts/spjs-utility/spjs-utility.js"></script>
<script type="text/javascript">
function updateTitleFromName(){
var q, res, uRes, count;
count = 0;
q = "<Where><IsNull><FieldRef Name='Title' /></IsNull></Where>";
res = spjs_QueryItems({"listName":_spPageContextInfo.pageListId,"query":q,"viewFields":["ID","FileLeafRef"]});
if(res.count === 0){
alert("No files without title found.");
return;
}
if(!confirm("There are "+res.count+" files to update. The page will appear as frozen while the script is working.\n\nContinue?")){
return;
}
$.each(res.items,function(i,item){
uRes = spjs_updateItem({"listName":_spPageContextInfo.pageListId,"id":item.ID,"data":{"Title":item.FileLeafRef.split(";#")[1]}});
if(!uRes.success){
alert("Could not update the file: "+item.FileLeafRef+" due to the follwing error:\n\n"+uRes.errorText);
}else{
count += 1;
}
});
alert("Updated "+count+" files.");
location.href = location.href;
}
</script>
The error is: TypeError: $spjs is null. And it occurs inside the library spjs-utility library on the spjs_QueryItems call.
Maybe this could be due to a conflictuous library that as added during the updated, but how can i debug this?
Also, if this doesn't work, wouldn't it be simpler to do the same with jQuery? Thats what i'm trying right now, but i'm a beginner as you must have perceived.
Thanks in advance.
Best
I would test if JQuery is loaded or not in your updateTitleFromName function:
if (window.jQuery) {
alert('loaded');
} else {
alert('not loaded');
}
if it is not loaded, try to reference your scripts with absolute urls to see if you can load them:
<script type="text/javascript" src="http://myportal/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://myportal/Scripts/spjs-utility/spjs-utility.js"></script>
I'm developping a web site using WAMP, this is a part of code in my website. I even checked this block of code mentioned below.
html page
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="Functions/jquery.min.js"></script>
<script type="text/javascript" src="Functions/listControl.js"></script>
<script type="text/javascript">
var users= new regUsers('load','bef','full');
</script>
</head>
<body>
</body>
</html>
javascript page
function regUsers(id,pos,detail)
{
/*
usr001 all users
usr002 search users on keyword
*/
var self=this
this.count=0;
this.id='#' + id;
this.pos=pos;
this.amount=0;
this.detail=detail;
this.countReset= function(){this.count = 0;};
this.getList=function()
{
console.log('count : ' + self.count);
$.ajax({
type:'POST',
url:'Functions/list.php',
data:{req:'usr001',off:this.count,detail:this.detail,amount:self.amount},
success:function(ans){
if(ans=="")
return;
else
{
self.count += parseInt(self.amount);
switch(self.pos)
{
case 'bef':
$(ans).insertBefore(self.id);
break;
case 'app':
$(self.id).append(ans);
console.log(ans);
break;
}
}
}
});
}
this.findRec=function(keyW='',cls,field)
{
if(keyW=='')
{
self.getList();
return;
}
$.ajax({
type:'POST',
url:'Functions/list.php',
data:{req:'usr002',keyW:keyW,detail:this.detail,field:field},
success:function(ans){
self.countReset();
$("."+ cls).remove();
switch(self.pos)
{
case 'bef':
$(ans).insertBefore(self.id);
break;
}
}
});
}
}
This code is properly work in Firefox, but not in internet explorer. In Internet explorer console, it is said that regUsers is not difined.
It could be that Internet Explore loads the JS files after it loads the inline script, I know it may not make much sense to do that but it might be a particular IE issue. What you could do is put your var users= new regUsers('load','bef','full'); in a third JS file or you can assign the value to users in unload of the body tag i.e.
<body onload="users = new regUsers('load', 'bet', 'full')">
. . .
</body>
This will insure that the your initialization code is executed after the webpage has loaded. Since users is declared with var it becomes a global variable, declaring with var users = … would have made it visible only in the scope of onload.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
if (window.self === window.top) { $.getScript("Wing.js"); }
</script>
</head>
</html>
Is there a way in C# to modify the above HTML file and convert it into this format:
<html>
<head>
</head>
</html>
Basically my goal is to remove all the JavaScript from the HTML page. I don't know what is be the best way to modify the HTML files. I want to do it programmatically as there are hundreds of files which need to be modified.
It can be done using regex:
Regex rRemScript = new Regex(#"<script[^>]*>[\s\S]*?</script>");
output = rRemScript.Replace(input, "");
May be worth a look: HTML Agility Pack
Edit: specific working code
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
string sampleHtml =
"<html>" +
"<head>" +
"<script type=\"text/javascript\" src=\"jquery.js\"></script>" +
"<script type=\"text/javascript\">" +
"if (window.self === window.top) { $.getScript(\"Wing.js\"); }" +
"</script>" +
"</head>" +
"</html>";
MemoryStream ms = new MemoryStream(Encoding.ASCII.GetBytes(sampleHtml));
doc.Load(ms);
List<HtmlNode> nodes = new List<HtmlNode>(doc.DocumentNode.Descendants("head"));
int childNodeCount = nodes[0].ChildNodes.Count;
for (int i = 0; i < childNodeCount; i++)
nodes[0].ChildNodes.Remove(0);
Console.WriteLine(doc.DocumentNode.OuterHtml);
I think as others have said, HtmlAgility pack is the best route. I've used this to scrape and remove loads of hard to corner cases. However, if a simple regex is your goal, then maybe you could try <script(.+?)*</script>. This will remove nasty nested javascript as well as normal stuff, i.e the type referred to in the link (Regular Expression for Extracting Script Tags):
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
if (window.self === window.top) { $.getScript("Wing.js"); }
</script>
<script> // nested horror
var s = "<script></script>";
</script>
</head>
</html>
usage:
Regex regxScriptRemoval = new Regex(#"<script(.+?)*</script>");
var newHtml = regxScriptRemoval.Replace(oldHtml, "");
return newHtml; // etc etc
This may seem like a strange solution.
If you don't want to use any third party library to do it and don't need to actually remove the script code, just kind of disable it, you could do this:
html = Regex.Replace(html , #"<script[^>]*>", "<!--");
html = Regex.Replace(html , #"<\/script>", "-->");
This creates an HTML comment out of script tags.
using regex:
string result = Regex.Replace(
input,
#"</?(?i:script|embed|object|frameset|frame|iframe|meta|link|style)(.|\n|\s)*?>",
string.Empty,
RegexOptions.Singleline | RegexOptions.IgnoreCase
);
I would like to print the content of a script tag is that possible with jquery?
index.html
<script type="text/javascript">
function sendRequest(uri, handler)
{
}
</script>
Code
alert($("script")[0].???);
result
function sendRequest(uri, handler)
{
}
Just give your script tag an id:
<div></div>
<script id='script' type='text/javascript'>
$('div').html($('#script').html());
</script>
http://jsfiddle.net/UBw44/
You can use native Javascript to do this!
This will print the content of the first script in the document:
alert(document.getElementsByTagName("script")[0].innerHTML);
This will print the content of the script that has the id => "myscript":
alert(document.getElementById("myscript").innerHTML);
Try this:
console.log(($("script")[0]).innerHTML);
You may use document.getElementsByTagName("script") to get an HTMLCollection with all scripts, then iterate it to obtain the text of each script. Obviously you can get text only for local javascript. For external script (src=) you must use an ajax call to get the text.
Using jQuery something like this:
var scripts=document.getElementsByTagName("script");
for(var i=0; i<scripts.length; i++){
script_text=scripts[i].text;
if(script_text.trim()!==""){ // local script text
// so something with script_text ...
}
else{ // external script get with src=...
$.when($.get(scripts[i].src))
.done(function(script_text) {
// so something with script_text ...
});
}
}
The proper way to get access to current script is document.scripts (which is array like HTMLCollection), the last element is always current script because they are processed and added to that list in order of parsing and executing.
var len = document.scripts.length;
console.log(document.scripts[len - 1].innerHTML);
The only caveat is that you can't use any setTimeout or event handler that will delay the code execution (because next script in html can be parsed and added when your code will execute).
EDIT: Right now the proper way is to use document.currentScript. The only reason not to use this solution is IE. If you're force to support this browser use original solution.
Printing internal script:
var isIE = !document.currentScript;
function renderPRE( script, codeScriptName ){
if (isIE) return;
var jsCode = script.innerHTML.trim();
// escape angled brackets between two _ESCAPE_START_ and _ESCAPE_END_ comments
let textsToEscape = jsCode.match(new RegExp("// _ESCAPE_START_([^]*?)// _ESCAPE_END_", 'mg'));
if (textsToEscape) {
textsToEscape.forEach(textToEscape => {
jsCode = jsCode.replace(textToEscape, textToEscape.replace(/</g, "<")
.replace(/>/g, ">")
.replace("// _ESCAPE_START_", "")
.replace("// _ESCAPE_END_", "")
.trim());
});
}
script.insertAdjacentHTML('afterend', "<pre class='language-js'><code>" + jsCode + "</code></pre>");
}
<script>
// print this script:
let localScript = document.currentScript;
setTimeout(function(){
renderPRE(localScript)
}, 1000);
</script>
Printing external script using XHR (AJAX):
var src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
// Exmaple from:
// https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
function reqListener(){
console.log( this.responseText );
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", src);
oReq.send();
*DEPRECATED*: Without XHR (AKA Ajax)
If you want to print the contents of an external script (file must reside on the same domain), then it's possible to use a <link> tag with the rel="import" attribute and then place the script's source in the href attribute. Here's a working example for this site:
<!DOCTYPE html>
<html lang="en">
<head>
...
<link rel="import" href="autobiographical-number.js">
...
</head>
<body>
<script>
var importedScriptElm = document.querySelector('link[rel="import"]'),
scriptText = scriptText.import.body.innerHTML;
document.currentScript.insertAdjacentHTML('afterend', "<pre>" + scriptText + "</pre>");
</script>
</body>
</html>
This is still experimental technology, part of web-components. read more on MDN