Cannot set up admins for facebook comments - meta-tags

We're having a weird issue on our website with facebook comments. It looks like the facebook scraper is incorrectly parsing (at least one of) our web pages so that it isn't picking up on admins to moderate the comments.
If you go to this link:
http://www.beliefnet.com/Espanol/10-Atletas-olimpicos-mas-inspiradores.aspx
and view source, you'll see that we have the appropriate tags in the head, including one for fb:admins. If I am logged into facebook on that account, I get no moderator options.
Running the page through facebook object debugger, I get an error that we have meta tags in the body. Specifically, this error:
Meta Tags In Body: You have tags ouside of your . This is either because
your was malformed and they fell lower in the parse tree, or you accidentally
put your Open Graph tags in the wrong place. Either way you need to fix it
before the tags are usable.
Looking at the scraped URL at the bottom of that page, I see what looks to be that facebook has 'reorganized' our html, and placed the meta tags from the head into the body.
Does anyone have any idea what is causing this? I thought that maybe we had some malformed html somewhere in the page that was throwing everything off, but I went through the html for that page and it looks good. Is there something else that i'm missing here?

Running your URL through validator.w3.org shows a few warning signs:
Line 77, Column 14: document type does not allow element "noscript" here; assuming missing "object" start-tag
Line 154, Column 699: document type does not allow element "meta" here
I was able to narrow down the (potential) issue to these lines in your page:
document.write('<a href="' + OAS.config.url + 'click_nx.ads/' + OAS.config.sitepage + '/1' + OAS.config.rns + '#' + OAS.config.listpos + '!' + pos + '?' + OAS.config.query + '" target=' + OAS.config.target + '>');
document.write('<img src="' + OAS.config.url + 'adstream_nx.ads/' + OAS.config.sitepage + '/1' + OAS.config.rns + '#' + OAS.config.listpos + '!' + pos + '?' + OAS.config.query + '" border=\"0\" /></a>');
These document.write() lines are also failing the w3.org validator:
Line 53, Column 197: character "+" is not allowed in the value of attribute "target"
Moreover, I think it's bad to use document.write() for DOM insertion (and because it can lead to blocking of page rendering).
Can you change to using js objects and DOM manipulation?
After FB fetches your URL, it runs it through a DOM parser that is probably choking when it encounters those document.write() lines. The fact that those lines have an <a> element spanning two document.writes() is probably confusing the parser. And the parser probably thinks it has reached the <body> of the page, thus the 'Meta tags in body' error.
As a quick test, try putting the fb:admins meta tag above those document.write() lines. Though, I wouldn't be surprised if the parser still chokes, but it's worth a try.
To test your page's html source, I used the simple script provided in a comment at the end of this php.net page:
http://www.php.net/manual/en/class.domxpath.php
It produced errors:
Unexpected end tag : a in /home/dlee/tmp/tmp.html, line: 54
Unexpected end tag : head in /home/dlee/tmp/tmp.html, line: 183
htmlParseStartTag: misplaced <body> tag in /home/dlee/tmp/tmp.html, line: 184
Where tmp.html was the html of your page saved to a file.
Line 54 is the previously mentioned document.write() line.
Let me know if any of the above results in progress, and I will edit this answer accordingly.

so the problem ultimately was that there was a <noscript>...</noscript> nested in the head, that was trying to include a tracking pixel for browsers without javascript enabled, as part of an ad service we use.
the issue should've been obvious looking at the output facebook gave us for 'how they see your page'. the body begins immediately after the script, but immediately before where the tag starts. apparently the facebook parser freaks out when it sees an element in the head that should be in the body, so it immediately starts the body there.
... facebook output ...
console.log(OAS);
})();
</script><!-- End OAS Setup --><!-- Begin comScore Tag --><script>
var _comscore = _comscore || [];
_comscore.push({ c1: "2", c2: "8428430" });
(function() {
var s = document.createElement("script"), el = document.getElementsByTagName("script")[0]; s.async = true;
s.src = (document.location.protocol == "https:" ? "https://sb" : "http://b") + ".scorecardresearch.com/beacon.js";
el.parentNode.insertBefore(s, el);
})();
</script>
</head>
<body>
<noscript>
</noscript>
<!-- End comScore Tag -->
... our html ...
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<asp:PlaceHolder id="OASHeader" runat="server" />
<!-- Begin comScore Tag -->
<script type="text/javascript">
var _comscore = _comscore || [];
_comscore.push({ c1: "2", c2: "8428430" });
(function() {
var s = document.createElement("script"), el = document.getElementsByTagName("script")[0]; s.async = true;
s.src = (document.location.protocol == "https:" ? "https://sb" : "http://b") + ".scorecardresearch.com/beacon.js";
el.parentNode.insertBefore(s, el);
})();
</script>
<!-- End comScore Tag -->
<noscript>
<img src="http://b.scorecardresearch.com/p?c1=2&c2=8428430&cv=2.0&cj=1" alt="" />
</noscript>
<script type="text/javascript">
....
<body>
....
so in the future, invalid head elements could definitely be causing this problem.

Related

My Chrome extension showing "Refused to execute inline event handler because it violates the following Content Security Policy directive" [duplicate]

This seems to be the easiest thing to do, but it's just not working. In a normal browser the .html and .js files works perfectly, but in the Chrome/Firefox extension the onClick function is not performing what it's supposed to do.
.js file:
function hellYeah(text) {
document.getElementById("text-holder").innerHTML = text;
}
.html file:
<!doctype html>
<html>
<head>
<title>
Getting Started Extension's Popup
</title>
<script src="popup.js"></script>
</head>
<body>
<div id="text-holder">
ha
</div>
<br />
<a onClick=hellYeah("xxx")>
hyhy
</a>
</body>
</html>
So basically once the user clicks "hyhy", "ha" should change into "xxx". And again - it works perfectly in the browser but does not work in the extension. Do you know why? Just in case I'm attaching the manifest.json below as well.
manifest.json:
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"http://api.flickr.com/"
]
}
Chrome Extensions don't allow you to have inline JavaScript (documentation).
The same goes for Firefox WebExtensions (documentation).
You are going to have to do something similar to this:
Assign an ID to the link (<a onClick=hellYeah("xxx")> becomes <a id="link">), and use addEventListener to bind the event. Put the following in your popup.js file:
document.addEventListener('DOMContentLoaded', function() {
var link = document.getElementById('link');
// onClick's logic below:
link.addEventListener('click', function() {
hellYeah('xxx');
});
});
popup.js should be loaded as a separate script file:
<script src="popup.js"></script>
Reason
This does not work, because Chrome forbids any kind of inline code in extensions via Content Security Policy.
Inline JavaScript will not be executed. This restriction bans both inline <script> blocks and inline event handlers (e.g. <button onclick="...">).
How to detect
If this is indeed the problem, Chrome would produce the following error in the console:
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.
To access a popup's JavaScript console (which is useful for debug in general), right-click your extension's button and select "Inspect popup" from the context menu.
More information on debugging a popup is available here.
How to fix
One needs to remove all inline JavaScript. There is a guide in Chrome documentation.
Suppose the original looks like:
<a onclick="handler()">Click this</a> <!-- Bad -->
One needs to remove the onclick attribute and give the element a unique id:
<a id="click-this">Click this</a> <!-- Fixed -->
And then attach the listener from a script (which must be in a .js file, suppose popup.js):
// Pure JS:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("click-this").addEventListener("click", handler);
});
// The handler also must go in a .js file
function handler() {
/* ... */
}
Note the wrapping in a DOMContentLoaded event. This ensures that the element exists at the time of execution. Now add the script tag, for instance in the <head> of the document:
<script src="popup.js"></script>
Alternative if you're using jQuery:
// jQuery
$(document).ready(function() {
$("#click-this").click(handler);
});
Relaxing the policy
Q: The error mentions ways to allow inline code. I don't want to / can't change my code, how do I enable inline scripts?
A: Despite what the error says, you cannot enable inline script:
There is no mechanism for relaxing the restriction against executing inline JavaScript. In particular, setting a script policy that includes 'unsafe-inline' will have no effect.
Update: Since Chrome 46, it's possible to whitelist specific inline code blocks:
As of Chrome 46, inline scripts can be whitelisted by specifying the base64-encoded hash of the source code in the policy. This hash must be prefixed by the used hash algorithm (sha256, sha384 or sha512). See Hash usage for <script> elements for an example.
However, I do not readily see a reason to use this, and it will not enable inline attributes like onclick="code".
I had the same problem, and didn´t want to rewrite the code, so I wrote a function to modify the code and create the inline declarated events:
function compile(qSel){
var matches = [];
var match = null;
var c = 0;
var html = $(qSel).html();
var pattern = /(<(.*?)on([a-zA-Z]+)\s*=\s*('|")(.*)('|")(.*?))(>)/mg;
while (match = pattern.exec(html)) {
var arr = [];
for (i in match) {
if (!isNaN(i)) {
arr.push(match[i]);
}
}
matches.push(arr);
}
var items_with_events = [];
var compiledHtml = html;
for ( var i in matches ){
var item_with_event = {
custom_id : "my_app_identifier_"+i,
code : matches[i][5],
on : matches[i][3],
};
items_with_events.push(item_with_event);
compiledHtml = compiledHtml.replace(/(<(.*?)on([a-zA-Z]+)\s*=\s*('|")(.*)('|")(.*?))(>)/m, "<$2 custom_id='"+item_with_event.custom_id+"' $7 $8");
}
$(qSel).html(compiledHtml);
for ( var i in items_with_events ){
$("[custom_id='"+items_with_events[i].custom_id+"']").bind(items_with_events[i].on, function(){
eval(items_with_events[i].code);
});
}
}
$(document).ready(function(){
compile('#content');
})
This should remove all inline events from the selected node, and recreate them with jquery instead.
I decide to publish my example that I used in my case. I tried to replace content in div using a script. My problem was that Chrome did not recognized / did not run that script.
In more detail What I wanted to do: To click on a link, and that link to "read" an external html file, that it will be loaded in a div section.
I found out that by placing the script before the DIV with ID that
was called, the script did not work.
If the script was in another DIV, also it does not work
The script must be coded using document.addEventListener('DOMContentLoaded', function() as it was told
<body>
<a id=id_page href ="#loving" onclick="load_services()"> loving </a>
<script>
// This script MUST BE under the "ID" that is calling
// Do not transfer it to a differ DIV than the caller "ID"
document.getElementById("id_page").addEventListener("click", function(){
document.getElementById("mainbody").innerHTML = '<object data="Services.html" class="loving_css_edit"; ></object>'; });
</script>
</body>
<div id="mainbody" class="main_body">
"here is loaded the external html file when the loving link will
be clicked. "
</div>
As already mentioned, Chrome Extensions don't allow to have inline JavaScript due to security reasons so you can try this workaround as well.
HTML file
<!doctype html>
<html>
<head>
<title>
Getting Started Extension's Popup
</title>
<script src="popup.js"></script>
</head>
<body>
<div id="text-holder">ha</div><br />
<a class="clickableBtn">
hyhy
</a>
</body>
</html>
<!doctype html>
popup.js
window.onclick = function(event) {
var target = event.target ;
if(target.matches('.clickableBtn')) {
var clickedEle = document.activeElement.id ;
var ele = document.getElementById(clickedEle);
alert(ele.text);
}
}
Or if you are having a Jquery file included then
window.onclick = function(event) {
var target = event.target ;
if(target.matches('.clickableBtn')) {
alert($(target).text());
}
}

POST FORM in node and receive data response back to same webpage

I have a webpage that takes form details, POSTS the data and should then show the results. I'm using express for my routing.
This all works fine by resending the data with the HTML template after the POST but I think there must be a better way by hiding the "results" HTML section then just showing it once the data is known from the form. I've shown a cutdown version of my pages below.
On first load, the page says "your result is undefined", which I would expect but is ugly.
I could remove the "result" section and create a 2nd HTML page to resend from the POST route with it in which would work but I think there must be a better way.
I want to hide the result section on 1st page load then make it appear on the button submit with the result data. I can get the section hide/unhide but I can't get the data results back to display them. On button submit the form results just appear in the weburl www.mywebsite.com/?data almost like a GET request
I have tried using FormData and npm 'form-data' in a POST but can't get it working following these examples https://javascript.info/formdata and https://www.npmjs.com/package/form-data.
My structure in Node is
Router.js file
return res.send(htmlFormTemplate({}));
});
router.post('/css',
[],
async (req, res) => {
let {data} = req.body;
///
result= do some calculation on {data}
///
return res.send(htmlFormTemplate({result}));
});
The htmlFormTemplate is a js file
module.exports = ({result}) => {
return `
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form class="box" method ="POST">
<inputname="data" />
<button>Submit</button>
</form>
<script>
///tried form processing here
</script>
<section id="Results">
<ul><li>Your result is ${result}</li></ul>
</section>
</body>
</html>
`;
};
I'm self-taught and new so hope this makes sense and thanks for any help/ideas
You can check if the result variable is null before it gets to the section div:
${ result === null ? '' :
`<section id="Results">
<ul><li>Your result is ${result}</li></ul>
</section>`}
Like this, it wont show the result div if result if null.
There is a very simple to solve this problem,
just use some templating engine for ex EJS, its very easy to use and will help you better,
and your result is undefined because your using a promise and it might have happened that the response might have not come and you loaded the page. Just use await
return await res.send(htmlFormTemplate({result}));

Angular8 How to add string to <head> in index.html

IN razor format, we can use #Html.Raw to add meta-tags from string, for example, in controller we can write;
Model header = new Model();
header = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">";
in Layout Page we can add the above string in <Head> section as
#Html.Raw(Model.header)
How can I do the same in Index.Html in Angular 8 (not using razor). The string "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"
is retrieved from DB and need to be appended to "<Head>" section in index.html. I do not have control over what will be provided from DB. But whatever will be the value it will be <Head> or section related, and may also include <scripts>.
Thanks
Found the answer, for someone who is also looking for this solution:
let fragment = document.createRange().createContextualFragment("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
document.head.append(fragment);

Anki and AnkiDroid: Importing JSON from collection.media with javascript

I want to import files from collection.media that are not sound, image, or video. For example I'd like to import a JSON file.
I put the file _script.jquery-3.3.1.min.js and _data.json in my collection.media folder.
On Anki Desktop (Ubuntu), the following works:
<script src="_script.jquery-3.3.1.min.js"></script>
<script>
$.getJSON('_data.json', function(data) {
// succeeds on Anki Desktop, fails on AnkiDroid
});
</script>
(Note on Anki Desktop 2.0.47 I am using the JS Booster plugin).
On AnkiDroid, the situation is different. JQuery loads just fine in the script tag. However, $.getJSON fails to find the _data.json file.
I'd like to use _data.json on many cards/notes.
How can I import non-media, non-js files from collection.media in javascript, in a way that works both in Anki Desktop and AnkiDroid?
I have found some working answer for this.
To get character data in AnkiDroid card templates. (OFFLINE)
As we can access js and image file using this
<script src="some-js-file.js"></script>
<img src="some-image.png"></img>
To access json
I have tried same steps but getting CORS error so I used next steps.
<!-- It will give CORS error -->
<script src="我.json" type="application/json"></script>
With example,
To access 我.json file
Copy contents of 我.json into a javascript file 我.js, with any variable name,
var char_data = {"strokes":["M 350 571 Q 3....}
Add following tag to access that js file
<!-- Note : file type & name -->
<script src="我.js" type="text/javascript"></script>
Now also change code in _hanzi-writer.min.js
To change code, first beautify code using this https://beautifier.io, then make following change
a) Remove the link to load from internet
b) Change this 200 != r.status and replace/add this
JSON.parse(JSON.stringify(char_data))
( May be more good replacement can be done here )
....
....
// Note : char_data variable come from 我.js file
r.overrideMimeType && r.overrideMimeType("application/json"), r.open("GET", "", !0), r.onerror = function(t) {
....
....
4 === r.readyState && (200 != r.status ? i(JSON.parse(JSON.stringify(char_data))) : 0 !== r.status && n && n(r))
....
....
So final script will be like this
Front side of card
{{Pinyin}}
<div id="character-target-div"></div>
<script src= "我.js" type="text/javascript"></script>
<script>
var data = JSON.stringify(char_data);
console.log(data);
</script>
<script src="_hanzi-writer.min.js"></script>
<script>
var writer = HanziWriter.create('character-target-div', '我', {
width: 150,
height: 150,
showCharacter: false,
padding: 5
});
writer.quiz();
</script>
Above all the steps are for single file 我.js
To access other character repeat the same.
For similar issues view my code
https://github.com/infinyte7/Anki-xiehanzi
https://github.com/infinyte7/hanzi-writer-data-in-javascript
I assume this is related to how AnkiDroid handles collections.media files. If so, this might be a bug. A really hackish workaround could be to rename the file to .svg so that AnkiDroid treats it as an image and lets it through.

How can I render inline JavaScript with Jade / Pug?

I'm trying to get JavaScript to render on my page using Jade (http://jade-lang.com/)
My project is in NodeJS with Express, eveything is working correctly until I want to write some inline JavaScript in the head. Even taking the examples from the Jade docs I can't get it to work what am I missing?
Jade template
!!! 5
html(lang="en")
head
title "Test"
script(type='text/javascript')
if (10 == 10) {
alert("working")
}
body
Resulting rendered HTML in browser
<!DOCTYPE html>
<html lang="en">
<head>
<title>"Test"</title>
<script type="text/javascript">
<if>(10 == 10) {<alert working></alert></if>}
</script>
</head>
<body>
</body>
</html>
Somethings definitely a miss here any ideas?
simply use a 'script' tag with a dot after.
script.
var users = !{JSON.stringify(users).replace(/<\//g, "<\\/")}
https://github.com/pugjs/pug/blob/master/packages/pug/examples/dynamicscript.pug
The :javascript filter was removed in version 7.0
The docs says you should use a script tag now, followed by a . char and no preceding space.
Example:
script.
if (usingJade)
console.log('you are awesome')
else
console.log('use jade')
will be compiled to
<script>
if (usingJade)
console.log('you are awesome')
else
console.log('use jade')
</script>
Use script tag with the type specified, simply include it before the dot:
script(type="text/javascript").
if (10 == 10) {
alert("working");
}
This will compile to:
<script type="text/javascript">
if (10 == 10) {
alert("working");
}
</script>
No use script tag only.
Solution with |:
script
| if (10 == 10) {
| alert("working")
| }
Or with a .:
script.
if (10 == 10) {
alert("working")
}
THIRD VERSION OF MY ANSWER:
Here's a multiple line example of inline Jade Javascript. I don't think you can write it without using a -. This is a flash message example that I use in a partial. Hope this helps!
-if(typeof(info) !== 'undefined')
-if (info)
- if(info.length){
ul
-info.forEach(function(info){
li= info
-})
-}
Is the code you're trying to get to compile the code in your question?
If so, you don't need two things: first, you don't need to declare that it's Javascript/a script, you can just started coding after typing -; second, after you type -if you don't need to type the { or } either. That's what makes Jade pretty sweet.
--------------ORIGINAL ANSWER BELOW ---------------
Try prepending if with -:
-if(10 == 10)
//do whatever you want here as long as it's indented two spaces from
the `-` above
There are also tons of Jade examples at:
https://github.com/visionmedia/jade/blob/master/examples/
script(nonce="some-nonce").
console.log("test");
//- Workaround
<script nonce="some-nonce">console.log("test");</script>
For multi-line content jade normally uses a "|", however:
Tags that accept only text such as
script, style, and textarea do not
need the leading | character
This said, i cannot reproduce the problem you are having. When i paste that code in a jade template, it produces the right output and prompts me with an alert on page-load.
Use the :javascript filter. This will generate a script tag and escape the script contents as CDATA:
!!! 5
html(lang="en")
head
title "Test"
:javascript
if (10 == 10) {
alert("working")
}
body

Resources