JavaScript function being blocked by office addin - javascript

I have an outlook add-in that I have created. In this add-in I am trying to make a button pull some data from a website using APIs.
I was able to do this on with a local test but when I put the code into my add-in nothing happens. It gives an error in the console that says Tracking Prevention blocked access to storage for https://appsforoffice.microsoft.com/lib/1/hosted/en-us/outlook_strings.js. but when I commented out my javascript code, that error still came up. So I don't know why my code is being blocked.
Picture of problem:
On my local computer it works no problem:
Here is my code:
javascript:
function freshdesktickets() {
Office.onReady((info) => {
// window.parent.location.reload()
const url = "https://alloysystems.freshdesk.com/api/v2/tickets";
fetch(url, {
method: "GET",
withCredentials: true,
headers: {
// needed to base64 encode my key with ":x" at the end of the api key then I used that for the authorization header.
"authorization": "Basic YOUWILLNEVERGETMYAPIKEYLOL"
}
})
.then(resp => resp.json())
.then(data => {let text = "";
const output = document.querySelector('span.ms-font-m');
for (let i = 0; i < data.length; i++) {
let text = "Subject: " + JSON.stringify(data[i].subject) + "<br>"+
"CC Emails: " + JSON.stringify(data[i].cc_emails).replace("[]","No Emails are CC'd").replace("[","").replace("]","") + "<br>" +
"Ticket Creation Date: " + JSON.stringify(data[i].created_at) + "<br>" +
"Ticket Status: " + JSON.stringify(data[i].status).replace("2", "Open").replace("3", "Pending").replace("4", "Resolved").replace("5", "Closed").replace("6", "Waiting On Customer") ;
let pre = document.createElement('pre');
pre.innerHTML = text;
pre.style.cssText += 'font-size:24px;font-weight:bold;'
output.appendChild(pre);
console.log(pre)
}
})})
}
HTML:
<div class="ms-PanelExample">
<script src="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/js/fabric.min.js"></script>
<button style="margin:1px;" id="get-freshdesk" class="ms-Button ms-Button--primary">
<span class="ms-Button-label">Freshdesk Tickets</span>
</button>
<div class="ms-Panel ms-Panel--xxl">
<button class="ms-Panel-closeButton ms-PanelAction-close">
<i class="ms-Panel-closeIcon ms-Icon ms-Icon--Cancel"></i>
</button>
<div class="ms-Panel-contentInner">
<p class="ms-Panel-headerText">Freshdesk Integration</p>
<div class="ms-Panel-content">
<span class="ms-font-m">Latest Ticket information</span>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var PanelExamples = document.getElementsByClassName("ms-PanelExample");
for (var i = 0; i < PanelExamples.length; i++) {
(function() {
var PanelExampleButton = PanelExamples[i].querySelector(".ms-Button");
var PanelExamplePanel = PanelExamples[i].querySelector(".ms-Panel");
PanelExampleButton.addEventListener("click", function(i) {
new fabric['Panel'](PanelExamplePanel);
});
}());
}
</script>
Result from console:
Tracking Prevention blocked access to storage for https://appsforoffice.microsoft.com/lib/1/hosted/en-us/outlook_strings.js.
### yet it displays the pre information in the console below because I added console.log(pre)
I also tried adding the domains of where the api gets its data but I am still getting the error. I added it to the edge's exclusion list and I also added it to the manifest xml.
code that was added to the manifest xml to ensure that the api's domain is allow to get some data:
<!-- Domains that will be allowed when navigating. For example, if you use ShowTaskpane and then have an href link, navigation will only be allowed if the domain is on this list. -->
<AppDomains>
<AppDomain>https://freshdesk.com</AppDomain>
<AppDomain>https://alloysystems.freshdesk.com</AppDomain>
<AppDomain>AppDomain3</AppDomain>
</AppDomains>
<!--End Basic Settings. -->

I think I figured out the answer. The problem is that I added the javascript to my existing office apps javascript which has Office.onReady((info) => at the top of the script. If I add my javascript to the existing office apps javascript it will fail.
So I made a new javascript file and added that to the html. In the new file I used the javascript code above, then I simply added the script to the head tag and it started working.

Related

Using Google Identity Service to create a sign up button but nothing is displayed in popup window

When I click on the "sign up with google button" nothing is displayed on the pop-up window.
I have gone through some of the previous posts in SO but they didn't fix this issue:
Links Visited
the-given-origin-is-not-allowed-for-the-given-client-id-gsi
gsi-logger-the-given-origin-is-not-allowed-for-the-given-client-id
Here is the output :
This the JS Authorized Origin Configuration
I'm using Django as backend and here is the code to display the google sign up button :
<html>
<head>
<script src="https://accounts.google.com/gsi/client" async defer></script>
</head>
<body>
<div id="g_id_onload" data-client_id="client_id" data-context="signup" data-ux_mode="popup" data-login_uri="http://localhost:8000/users/register/signinWithGoogle" data-nonce="" data-auto_prompt="false">
</div>
<div class="g_id_signin" data-type="standard" data-shape="rectangular" data-theme="outline" data-text="signup_with" data-size="large" data-logo_alignment="left">
</div>
</body>
</html>
Django settings.py configuration :
SECURE_REFERRER_POLICY = "no-referrer-when-downgrade"
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'
Why is the "sign up with google" button not working am I missing something and how we can fix it?
If you don't mind using Javascript for your Google Sign In, you can follow these steps that I had to undertake to achieve the entire flow. You would also need to add your localhost to the Authorized origins which I believe you are doing.:
First create a button that will hold the HTML element:
<button id="btnGoogleSignIn" style="border:none;background: none;"> </button>
You can then use the below script and associated functions in which I am getting the JWT token from Google and then decoding it to get the required information out like email address etc. Note that I am calling the onSignInGSI as callback on the button initialization.
<script>
function decodeJwtResponseFromGoogleAPI(token) {
let base64Url = token.split('.')[1]
let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
let jsonPayload =
decodeURIComponent(atob(base64).split('').map(function (c) {
return '%' + ('00' +
c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
return JSON.parse(jsonPayload)
}
function onSignInGSI(response) {
//console.log(response)
responsePayload = decodeJwtResponseFromGoogleAPI(response.credential);
console.log("ID: " + responsePayload.sub);
console.log('Full Name: ' + responsePayload.name);
console.log('Given Name: ' + responsePayload.given_name);
console.log('Family Name: ' + responsePayload.family_name);
console.log("Image URL: " + responsePayload.picture);
console.log("Email: " + responsePayload.email);
}
window.onload = function () {
google.accounts.id.initialize({
client_id: client_id,
context: 'signin',
callback: onSignInGSI
});
google.accounts.id.prompt((notification) => {
if (notification.isNotDisplayed() || notification.isSkippedMoment()) {
document.cookie = `g_state=;path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT`;
google.accounts.id.prompt()
}
});
google.accounts.id.renderButton(document.getElementById("btnGoogleSignIn"),
{
type: "standard",
text: "signin_with",
logo_alignment: "left",
width: 375
});
};
</script>
<script src="https://accounts.google.com/gsi/client" async defer></script>
For more configuration options on the button you can refer here:
from the details you had mentioned, Auth code flow failed as soon as it started due to unauthorized origin.
As per the message "m=credential_page_library:45 [GSI_LOGGER]: The given origin is not allowed for the given client ID" you had mentioned,
you need to add "http://localhost:8000/users/register/signinWithGoogle" to authorized javascript origins.
Also you need to validate that client id you are using is correct.
The error occurs for apps with "Publishing Status = In production" when your "Authorized JavaScript origin" does not start with https:// but with http://.
http://my.server.name:8000 is not accepted, a message is shown:
Invalid Origin: This app has a publishing status of "In production". URI must use https:// as the scheme.
http://localhost:8000 shows no such message, but still leads to the error.
https://my.server.name:8000 works.
Strangely, when "Publishing Status = Testing", the behavior is the same, except that the message for http://my.server.name:8000 does not appear.
(The Publishing Status of an app is maintained in the Google Cloud console under "APIs and Services > OAuth consent screen".)

React fetch() not working on mobile only

I'm an intern assisting on developing a simple landing page for our company. The main page is essentially a search bar, and as a user types if their query matches a credit union in our database, the name of that credit union is output below with a link to its page. Imagine a google-esque search bar.
This works great on desktop but for some reason, on mobile when a user types in a query, nothing comes up at all, even if they're typing something that most definitely exists in our database.
To see the site in action, it's http://mycuapp.com .
Here is the relevant HTML:
<Search></Search>
<div id = "results-bar" class="hidden"></div>
and the JS:
handleTyping(event) {
event.preventDefault();
event.stopPropagation();
const data = new FormData(event.target);
var query = event.target.value;
var url = "/search/" + query;
var i;
if (query.length >= 3) {
fetch(url, {
method: "GET",
}).then((value) => {
return value.json();
}).then((Response)=>{
var item = document.getElementById("results-bar");
if(item.className=='hidden'){
item.className = 'unhidden' ;
clickedButton.value = 'hide';
}
for (i = 0; i < Response.payload.length; i++){
var displayName = Response.payload[i].displayName;
var cuURL = Response.payload[i].url;
if(document.getElementById("results-bar").innerHTML.indexOf(displayName) == -1){ //not yet displayed in search results
var result = "<div class = 'result'><a href='" + cuURL + "'><p>" + displayName + "</p></a></div>";
document.getElementById("results-bar").innerHTML += result;
}
console.log(Response.payload[i].displayName);
}
});
}
}
render() {
return (
<form className="" id="search-form">
<input onKeyUp={this.handleTyping} type="text" autoComplete="off" name="query" placeholder="Search your credit union's name to download the mobile banking app."/>
</form>
);
}
Any insight would be greatly appreciated, including any suggestions on how to debug the problem from an iPhone (bc when simulated with Chrome's developer tools there is no issue).
EDIT: Turns out the problem is the line "const data = new FormData(event.target);" FormData is incompatible with Safari, or something. Our lead programmer caught it. Once we got rid of that line everything works great! Thanks everyone for your help.
Seems like you are trying to use Response stream which is not fully supported on Mobile Safari.
https://developer.mozilla.org/en-US/docs/Web/API/Response
Alternatively you can use fetch polyfill which is supported in Safari 6.1+
https://github.com/github/fetch
FormData: https://developer.mozilla.org/en-US/docs/Web/API/FormData
Is not compatible with Safari Mobile.

Javascript bookmarklet to send url of current page to bing

A bookmarklet is a bookmark whose address is JavaScript code.
I would like to get the URL of the current page I am on and paste that into the text box of the Bing search page.
I can get the URL easily enough:
javascript:(function(){var%20url=window.location.href;alert(url);})();
But then how do I set the text box on the Bing page to my variable, url and then make it search?
This does not work:
javascript:(function(){var%20url=window.location.href;window.open%20("https://www.bing.com/search?q=&url");})();
Use the following bookmarklet code:
javascript:{window.location='http://bing.com/search?q='+encodeURIComponent(window.location.href)}
Of course you can do the way you have seen above. However, I have been in this situation where I wanted to control what to show from within my application.
Then I decided to connect my application from Bing API. The benefit is that it is free and you will not take user away from your website.
You will need to get the API Key from the Azure Market Place
Here is the code that you might want to give it a try , may be, in the future.
<html>
<head>
<title>BING API Integration</title>
<SCRIPT type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#searchButton').click(function(e){
$("#results").empty();
var query=$('#searchTerm').val();
if ( query) {
serviceOp = "Web";
search(query, serviceOp);
}
});
});
function search(query, serviceOp){
// your account key that youw ill get from https://datamarket.azure.com
var acctKey = '<Your Key>';
var rootUri = 'https://api.datamarket.azure.com/Bing/Search';
var requestUri = rootUri + "/" + serviceOp + "?$format=json&Query='" + query + "'";
$.ajax({
type: "GET",
url: requestUri,
headers: {
"Authorization": "Basic " + window.btoa(acctKey + ":" + acctKey)
},
}).done(function(o){
if ( o.d !== undefined){
var items = o.d.results;
for(var idx=0, len= items.length; idx < len; idx++ ){
var item = items[idx];
switch(item.__metadata.type){
case 'WebResult':
showWebResult(item);
}
}
}
});
}
// Shows one item of Web result.
function showWebResult(item) {
var p = document.createElement('p');
var a = document.createElement('a');
a.href = item.Url;
$(a).append(item.Title);
$(p).append(item.Description);
$('#results').append(a, p);
}
</script>
</head>
<body>
<label for="searchTerm">Search: </label>
<input id="searchTerm" type="text"/>
<button id="searchButton">Search</button>
<div id="results">
</div>
</body>
</html>

Warning in Chrome when loading Pinterest pinit.js file

Getting the following warning when trying to load Pinterest API JS code:
Resource interpreted as Script but transferred with MIME type text/plain: "http://widgets.pinterest.com/v3/pidgets/log/?via=http%3A%2F%2Fsamplesiteā€¦are%2F&type=pidget&callback=PIDGET_1361830898800.f.devNull&t=1361830898802".
Accessing the script:
<script type="text/javascript" src="//assets.pinterest.com/js/pinit.js"></script>
Also have this code:
$(".div5").append('<div class="pin-it"><a id="pinterest_a" data-pin-config="above" href="//pinterest.com/pin/create/button/?url=' + source_url + '&media=' + source_image + '&description=' + image_description + '" data-pin-do="buttonPin" ><img src="//assets.pinterest.com/images/pidgets/pin_it_button.png" /></a></div>');
var element = document.getElementById('pinterest_a');
try{
(function (x) {
for (var n in x)
if (n.indexOf('PIN_') == 0)
return x[n];
return null;
})(window).f.render.buttonPin(element);
}
catch (e) {
//catch and just suppress error
}
Using Google Chrome
It's a minor issue with the way Pinterest has their web service set up. You can safely ignore it.

How to parse an RSS feed using JavaScript?

I need to parse an RSS feed (XML version 2.0) and display the parsed details in an HTML page.
Parsing the Feed
With jQuery's jFeed
(Don't really recommend that one, see the other options.)
jQuery.getFeed({
url : FEED_URL,
success : function (feed) {
console.log(feed.title);
// do more stuff here
}
});
With jQuery's Built-in XML Support
$.get(FEED_URL, function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
With jQuery and the Google AJAX Feed API
$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(FEED_URL),
dataType : 'json',
success : function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("author : " + e.author);
console.log("description: " + e.description);
});
}
}
});
But that means you're relient on them being online and reachable.
Building Content
Once you've successfully extracted the information you need from the feed, you could create DocumentFragments (with document.createDocumentFragment() containing the elements (created with document.createElement()) you'll want to inject to display your data.
Injecting the content
Select the container element that you want on the page and append your document fragments to it, and simply use innerHTML to replace its content entirely.
Something like:
$('#rss-viewer').append(aDocumentFragmentEntry);
or:
$('#rss-viewer')[0].innerHTML = aDocumentFragmentOfAllEntries.innerHTML;
Test Data
Using this question's feed, which as of this writing gives:
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:re="http://purl.org/atompub/rank/1.0">
<title type="text">How to parse a RSS feed using javascript? - Stack Overflow</title>
<link rel="self" href="https://stackoverflow.com/feeds/question/10943544" type="application/atom+xml" />
<link rel="hub" href="http://pubsubhubbub.appspot.com/" />
<link rel="alternate" href="https://stackoverflow.com/q/10943544" type="text/html" />
<subtitle>most recent 30 from stackoverflow.com</subtitle>
<updated>2012-06-08T06:36:47Z</updated>
<id>https://stackoverflow.com/feeds/question/10943544</id>
<creativeCommons:license>http://www.creativecommons.org/licenses/by-sa/3.0/rdf</creativeCommons:license>
<entry>
<id>https://stackoverflow.com/q/10943544</id>
<re:rank scheme="http://stackoverflow.com">2</re:rank>
<title type="text">How to parse a RSS feed using javascript?</title>
<category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="javascript"/><category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="html5"/><category scheme="https://stackoverflow.com/feeds/question/10943544/tags" term="jquery-mobile"/>
<author>
<name>Thiru</name>
<uri>https://stackoverflow.com/users/1126255</uri>
</author>
<link rel="alternate" href="https://stackoverflow.com/questions/10943544/how-to-parse-a-rss-feed-using-javascript" />
<published>2012-06-08T05:34:16Z</published>
<updated>2012-06-08T06:35:22Z</updated>
<summary type="html">
<p>I need to parse the RSS-Feed(XML version2.0) using XML and I want to display the parsed detail in HTML page, I tried in many ways. But its not working. My system is running under proxy, since I am new to this field, I don't know whether it is possible or not. If any one knows please help me on this. Thanks in advance.</p>
</summary>
</entry>
<entry>
<id>https://stackoverflow.com/questions/10943544/-/10943610#10943610</id>
<re:rank scheme="http://stackoverflow.com">1</re:rank>
<title type="text">Answer by haylem for How to parse a RSS feed using javascript?</title>
<author>
<name>haylem</name>
<uri>https://stackoverflow.com/users/453590</uri>
</author>
<link rel="alternate" href="https://stackoverflow.com/questions/10943544/how-to-parse-a-rss-feed-using-javascript/10943610#10943610" />
<published>2012-06-08T05:43:24Z</published>
<updated>2012-06-08T06:35:22Z</updated>
<summary type="html"><h1>Parsing the Feed</h1>
<h3>With jQuery's jFeed</h3>
<p>Try this, with the <a href="http://plugins.jquery.com/project/jFeed" rel="nofollow">jFeed</a> <a href="http://www.jquery.com/" rel="nofollow">jQuery</a> plug-in</p>
<pre><code>jQuery.getFeed({
url : FEED_URL,
success : function (feed) {
console.log(feed.title);
// do more stuff here
}
});
</code></pre>
<h3>With jQuery's Built-in XML Support</h3>
<pre><code>$.get(FEED_URL, function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
</code></pre>
<h3>With jQuery and the Google AJAX APIs</h3>
<p>Otherwise, <a href="https://developers.google.com/feed/" rel="nofollow">Google's AJAX Feed API</a> allows you to get the feed as a JSON object:</p>
<pre><code>$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&amp;num=10&amp;callback=?&amp;q=' + encodeURIComponent(FEED_URL),
dataType : 'json',
success : function (data) {
if (data.responseData.feed &amp;&amp; data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("author : " + e.author);
console.log("description: " + e.description);
});
}
}
});
</code></pre>
<p>But that means you're relient on them being online and reachable.</p>
<hr>
<h1>Building Content</h1>
<p>Once you've successfully extracted the information you need from the feed, you need to create document fragments containing the elements you'll want to inject to display your data.</p>
<hr>
<h1>Injecting the content</h1>
<p>Select the container element that you want on the page and append your document fragments to it, and simply use innerHTML to replace its content entirely.</p>
</summary>
</entry></feed>
Executions
Using jQuery's Built-in XML Support
Invoking:
$.get('https://stackoverflow.com/feeds/question/10943544', function (data) {
$(data).find("entry").each(function () { // or "item" or whatever suits your feed
var el = $(this);
console.log("------------------------");
console.log("title : " + el.find("title").text());
console.log("author : " + el.find("author").text());
console.log("description: " + el.find("description").text());
});
});
Prints out:
------------------------
title : How to parse a RSS feed using javascript?
author :
Thiru
https://stackoverflow.com/users/1126255
description:
------------------------
title : Answer by haylem for How to parse a RSS feed using javascript?
author :
haylem
https://stackoverflow.com/users/453590
description:
Using jQuery and the Google AJAX APIs
Invoking:
$.ajax({
url : document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('https://stackoverflow.com/feeds/question/10943544'),
dataType : 'json',
success : function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
console.log("------------------------");
console.log("title : " + e.title);
console.log("author : " + e.author);
console.log("description: " + e.description);
});
}
}
});
Prints out:
------------------------
title : How to parse a RSS feed using javascript?
author : Thiru
description: undefined
------------------------
title : Answer by haylem for How to parse a RSS feed using javascript?
author : haylem
description: undefined
Another deprecated (thanks to #daylight) option, and the easiest for me (this is what I'm using for SpokenToday.info):
The Google Feed API without using JQuery and with only 2 steps:
Import the library:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">google.load("feeds", "1");</script>
Find/Load feeds (documentation):
var feed = new google.feeds.Feed('http://www.google.com/trends/hottrends/atom/feed?pn=p1');
feed.load(function (data) {
// Parse data depending on the specified response format, default is JSON.
console.dir(data);
});
To parse data, check documentation about the response format.
If you are looking for a simple and free alternative to Google Feed API for your rss widget then rss2json.com could be a suitable solution for that.
You may try to see how it works on a sample code from the api documentation below:
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("https://news.ycombinator.com/rss");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.appendChild(document.createTextNode(entry.title));
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(initialize);
<html>
<head>
<script src="https://rss2json.com/gfapi.js"></script>
</head>
<body>
<p><b>Result from the API:</b></p>
<div id="feed"></div>
</body>
</html>
If you want to use a plain javascript API, there is a good example at https://github.com/hongkiat/js-rss-reader/
The complete description at https://www.hongkiat.com/blog/rss-reader-in-javascript/
It uses fetch method as a global method that asynchronously fetches a resource. Below is a snap of code:
fetch(websiteUrl).then((res) => {
res.text().then((htmlTxt) => {
var domParser = new DOMParser()
let doc = domParser.parseFromString(htmlTxt, 'text/html')
var feedUrl = doc.querySelector('link[type="application/rss+xml"]').href
})
}).catch(() => console.error('Error in fetching the website'))
For anyone else reading this (in 2019 onwards) unfortunately most JS RSS reading implementations don't now work. Firstly Google API has shut down so this is no longer an option and because of the CORS security policy you generally cannot now request RSS feeds cross-domains.
Using the example on https://www.raymondcamden.com/2015/12/08/parsing-rss-feeds-in-javascript-options (2015) I get the following:
Access to XMLHttpRequest at 'https://feeds.feedburner.com/raymondcamdensblog?format=xml' from origin 'MYSITE' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is correct and is a security precaution by the end website but does now mean that the answers above are unlikely to work.
My workaround will probably be to parse the RSS feed through PHP and allow the javascript to access my PHP rather than trying to access the end-destination feed itself.
I was so exasperated by many misleading articles and answers that I wrote my own RSS reader:
https://gouessej.wordpress.com/2020/06/28/comment-creer-un-lecteur-rss-en-javascript-how-to-create-a-rss-reader-in-javascript/
You can use AJAX requests to fetch the RSS files but it will work if and only if you use a CORS proxy. I'll try to write my own CORS proxy to give you a more robust solution. In the meantime, it works, I deployed it on my server under Debian Linux.
My solution doesn't use JQuery, I use only plain Javascript standard APIs with no third party libraries and it's supposed to work even with Microsoft Internet Explorer 11.
You can use jquery-rss or Vanilla RSS, which comes with nice templating and is super easy to use:
// Example for jquery.rss
$("#your-div").rss("https://stackoverflow.com/feeds/question/10943544", {
limit: 3,
layoutTemplate: '<ul class="inline">{entries}</ul>',
entryTemplate: '<li>[{author}#{date}] {title}<br/>{shortBodyPlain}</li>'
})
// Example for Vanilla RSS
const RSS = require('vanilla-rss');
const rss = new RSS(
document.querySelector("#your-div"),
"https://stackoverflow.com/feeds/question/10943544",
{
// options go here
}
);
rss.render().then(() => {
console.log('Everything is loaded and rendered');
});
See http://jsfiddle.net/sdepold/ozq2dn9e/1/ for a working example.
Trying to find a good solution for this now, I happened upon the FeedEk jQuery RSS/ATOM Feed Plugin that does a great job of parsing and displaying RSS and Atom feeds via the jQuery Feed API. For a basic XML-based RSS feed, I've found it works like a charm and needs no server-side scripts or other CORS workarounds for it to run even locally.
I did not find a solution for parsing RSS just with js due to CORS error I kept receiving. Installing a plugin is not an option for me and building a proxy is not fun either and the small solutions I found didn't work.
So just in case someone is getting here and can use server-side, I found this solution in PHP that worked for me perfectly! (without the CORS error! "x has been blocked by CORS policy...")

Categories