Userscript to open Feedly article in new tab not working

On the RSS site Feedly, clicking an article defaults to opening an on-page preview of the article. In order to open the full article in a new tab, the user must ctrl+click. I’m trying to write a simple userscript to automatically open a clicked article in a new tab, but I’m not experienced with combining JS and HTML.

This is an example of the outer HTML for one article:

<article id="fLHFtwryZugkTI3NC4UrLqmHQcckXfXbVh1XRHy9YeE=_17e8e258822:19cca6e:c8b06589_main" class="entry entry--selected entry--unread u5 density-24" data-alternate-link="https://www.theguardian.com/science/2022/jan/24/james-webb-space-telescope-station-a-million-miles-from-earth"
  data-navigation="inline" data-inlineentryid="fLHFtwryZugkTI3NC4UrLqmHQcckXfXbVh1XRHy9YeE=_17e8e258822:19cca6e:c8b06589" data-u="5">
  <div class="visual-container">
    <div class="visual" style="background-image: url(&quot;https://lh3.googleusercontent.com/b4TTLa9CuY9dHVaGhVo4pjMIBcuVDJvreIiCjB-X3ier6g_MQmyF7ivmfXu0gsyN0w6JAQMVJ_Oy4q5gol3MYsRN7QsW8zVayHHWYhZn=s347&quot;);"></div>
    <div class="visual-overlay"></div>
  </div>
  <div class="content"><a class="link entry__title" href="https://www.theguardian.com/science/2022/jan/24/james-webb-space-telescope-station-a-million-miles-from-earth" target="_blank" rel="noopener noreferrer">James Webb Space Telescope takes up station a million miles from Earth</a>
    <div
      class="EntryToolbar dark"><button aria-label="Read Later" class="EntryReadLaterButton EntryReadLaterButton--dark button-icon-only" type="button"><span class="button__icon-wrapper"><svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="icon icon-white"><path d="M16 2.929H8a2.5 2.5 0 0 0-2.5 2.5v16l.007.084a.5.5 0 0 0 .723.36l5.777-2.998 5.762 2.997a.5.5 0 0 0 .731-.443v-16a2.5 2.5 0 0 0-2.5-2.5Zm0 1 .144.006A1.5 1.5 0 0 1 17.5 5.43v15.176l-5.261-2.737-.09-.036a.5.5 0 0 0-.371.036L6.5 20.606V5.429a1.5 1.5 0 0 1 1.5-1.5h8Z" fill="currentColor" fill-rule="nonzero"></path></svg></span></button>
      <div
        class="fx tag-button"><button aria-label="Save to Board" class="tag-button__button EntryToolbar__tag-button EntryToolbar__tag-button--dark tag-button__button--dark button-icon-only" type="button"><span class="button__icon-wrapper"><svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="icon icon-white"><g fill="currentColor" fill-rule="nonzero"><path d="M11.48 2.78a.5.5 0 0 1 .85-.08l.047.08 2.797 5.687 6.256.918a.5.5 0 0 1 .333.788l-.056.065-2.47 2.413a.5.5 0 0 1-.757-.646l.059-.069 1.746-1.709-5.516-.808a.5.5 0 0 1-.324-.191l-.052-.083-2.465-5.012-2.464 5.012a.5.5 0 0 1-.282.25l-.094.024-5.517.808 3.993 3.904a.5.5 0 0 1 .15.345l-.007.097-.942 5.511 4.93-2.602a.5.5 0 0 1 .627.133l.049.076a.5.5 0 0 1-.133.626l-.076.05-5.827 3.075a.5.5 0 0 1-.734-.446l.008-.08 1.068-6.253-4.527-4.425a.5.5 0 0 1 .194-.833l.083-.02 6.255-.918 2.798-5.688Z"></path><path d="M17 13.5a.5.5 0 0 1 .492.41l.008.09v6a.5.5 0 0 1-.992.09L16.5 20v-6a.5.5 0 0 1 .5-.5Z"></path><path d="M20 16.5a.5.5 0 0 1 .09.992L20 17.5h-6a.5.5 0 0 1-.09-.992L14 16.5h6Z"></path></g></svg></span></button></div>
  <button
    aria-label="Mark as Read" class="EntryMarkAsReadButton EntryMarkAsReadButton--dark button-icon-only" type="button"><span class="button__icon-wrapper"><svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="icon icon-white"><path d="M20.215 5.65a.5.5 0 0 1 .77.63l-.057.07-11.786 12a.5.5 0 0 1-.643.06l-.07-.06-5.357-5.454a.5.5 0 0 1 .645-.76l.068.06 5 5.09L20.216 5.65Z" fill="currentColor" fill-rule="nonzero"></path></svg></span></button>
    <button
      aria-label="Mark as Read and Hide" class="EntryHideButton EntryHideButton--dark button-icon-only" type="button"><span class="button__icon-wrapper"><svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" class="icon icon-white"><g fill="currentColor" fill-rule="nonzero"><path d="M4.79 4.79a.5.5 0 0 1 .637-.059l.07.058L19.21 18.504a.5.5 0 0 1-.638.765l-.07-.058L4.79 5.496a.5.5 0 0 1 0-.707Z"></path><path d="M18.504 4.79a.5.5 0 0 1 .765.637l-.058.07L5.496 19.21a.5.5 0 0 1-.765-.638l.058-.07L18.504 4.79Z"></path></g></svg></span></button>
      </div>
      <div class="metadata EntryMetadata">
        <div class="EntryMetadataBasic__source-info"><span class="EntryEngagement EntryEngagement--no-icon" title="metric showing how popular this article is">24</span><a class="link entry__source" href="https://www.theguardian.com/uk">The Guardian</a> / <span class="EntryMetadataAgo ago lessThanAnHour"
            title="Published: Mon, 24 Jan 2022 22:03:21 GMT
Received: Mon, 24 Jan 2022 22:12:11 GMT"> 25min</span></div>
      </div>
      <div class="summary"> $10bn observatory manoeuvred into position at four times the orbit of the moon, with first images expected in June The world’s largest and most powerful telescope has reached its final destination – an observation post one million miles away from
        Earth. Nasa’s $10bn James Webb Space Telescope launched on Christmas Day last year from French Guiana on a quest to behold the dawn of the universe. Due</div>
      </div>
</article>

and this is the userscript (JS) I have so far.

var inputs = document.getElementsByTagName('input');

for (var i = 0; i < inputs.length; i++) {
  inputs[i].addEventListener("click", function(e) {
    e.preventDefault;
    var dest = inputs[i].attr("data-alternate-link");
    window.open(dest, '_blank');
  });
}

Can anyone help me troubleshoot this code?

When / how to sync Front End data with Backend Database

I just want to throw this out there to see what more experienced coders think…

I am working on my second Full Stack application, a ToDo App (don’t judge me). And again I find myself struggling to choose which approach to go with for getting user input into the Back End DB.

On one extreme, I could do Create/Update calls with every user keystroke.

  • PRO: User would have very low risk of loosing data if loosing internet connectivity in the middle of managing ToDo’s.
  • CON: High latency on Front End…? Heavy demand on Back End especially with hundreds of thousands of Users…?

On the other extreme, I could only do the Create/Update/Delete calls to the Back End when the user clicks an “Update” button, or when logging out.

  • PRO: Probably the best in terms of latency and server workload.
  • CON: High likelihood of data loss if users PC, Browser, or Network fails.

I know there is no one right way to do this, and there are many different approaches between the two extremes I listed above.

I’m just looking to start a discussion so we all can learn what the more experienced developers think. Is there a “Common Practice” for this kind of thing?

I thank you all in advance for your thoughts.

Asynchronous recursive JavaScript function returns same value and terminates abruptly

Every time I run the following function, I expect it to output the different paths embedded in my composer.json file and then perform this recursively for each package. However, it just gives me the same result over and over again. Please what am I missing here?

const packageComposer = async (node) => {
    node = node ? __dirname : node;
    let composer = fs.readFileSync(node + '/composer.json', 'utf8');
    let dependencies = Object.keys(JSON.parse(composer).require);
    console.log(node + '/composer.json');
    dependencies.forEach(key => {
        let dependency = key.split('/');
        let dir = node + '/vendor/' + dependency[0] + '/' + dependency[1];
        if (fs.existsSync(dir)) {
            packageComposer(dir);
        }
    });
}

Problems extracting information of a Promise Object React JS

I am doing a News Search Engine, using React + JS and I have some problems extracting information. Let’s first of all check out the main components of my app.

Here I obtain the sections of the most viewed news of the last 7 days in the NY Times (https://developer.nytimes.com/docs/most-popular-product/1/overview I am using this API). So this is my getSections() service:

export default function getSections () {

    const URL= `https://api.nytimes.com/svc/mostpopular/v2/viewed/7.json?api-key=${API_KEY}`;

    
  return fetch(URL)
        .then(res=>res.json())
        .then(response=> {
            const { data = [] } = response;
            if(Array.isArray(data)){
                const {results} = response; 
                console.log(results);
                const sections = results.map(result=>{
                    const { section } = result;
                    return section; 
                  });
                return sections;
            }
        })


};

And, later, I want to obtain the news filtered by section. In order to do that, I have other service implemented: getNewsFilteredBySection()

export default async function getNewsFilteredBySection (sectionSearched="") {

    const URL= `https://api.nytimes.com/svc/mostpopular/v2/viewed/7.json?api-key=${API_KEY}`;
   
    
  return fetch(URL)
        .then(res=>res.json())
        .then(response=> {
            const { data = [] } = response;
            if(Array.isArray(data)){
                const {results} = response; 
                const filteredResults = results.filter(obj => {
                    return obj.section === sectionSearched;
                  });
                console.log(filteredResults);
                return filteredResults;
            }
        })


};

And I need a helper, to extract the attributes I exactly want from filteredResults. That is my getNewsAttributes():

export function getNewsAttributes (filteredResultsJSON=[]) {
        const newsAttributes = JSON.parse(filteredResultsJSON).map(filteredResultJSON=>{
            const { title, abstract, url } = filteredResultJSON;
            console.log(title, abstract, url);
            return {title, abstract, url}; 
          });
        return newsAttributes;
};

I would like you to show my components structure. My App component:

function App() {

  const [section, setSection] = useState([]);

  useEffect(() => {
    getSections().then(sections=>setSection(sections));  
  }, [])

  return (
    <div>
      <Navbar/>
      <ListOfSections section={section}></ListOfSections>
    </div>
  );
}

export default App;

Here my ListOfSections component:

export default function ListOfSections ({section}) {

   const sectionFiltered = section.filter(onlyUnique);


  return (
    <div className="container_list_sections mt-4 ml-4">
        {     
            sectionFiltered.map((section)=> 
                <Section 
                    section={section}
                    // TODO: Create a generator of unique id and send it to section component
                />
            )
        }
    </div>
  )


};

Here my Section component:

export default function Section ({section}) {

    function showEvent (e) {
  console.log("pasa por aquí");
  const sectionSearched = e.target.innerText;
  const filteredResults = getNewsFilteredBySection(sectionSearched);
  console.log(`filteredResults:" ${filteredResults}`);
  const newsAttributes = getNewsAttributes(filteredResults);
  console.log(`newsAttributes ${newsAttributes}`)
  const {title, abstract, url} = newsAttributes;
  console.log (title, abstract, url);

    }

  return (
    <div className="animate__animated animate__fadeIn animate__slower"> 
        <h3 className="section-container mr-4 mb-4 pointer"
            onClick={showEvent}
            >{section}</h3>
    </div>
  )


};

And here my News component, still not working properly:

export default function News ({section}) {

  return (
    <div>
        <h3 className="section-container mr-4 mb-4 pointer">{section}</h3>
    </div>
  )


};

So, my problem is:

·The last console.log of the Section component which console shows is the next one: console.log(filteredResults:" ${filteredResults}); showing in console filteredResults:” [object Promise]. No further lines of that method are shown (I have several console.log) so I might have some errors but I dont know where. My goal is to extract the following information from the object: const {title, abstract, url} = newsAttributes;` to be able to render news with that props. Any idea where am I committing errors? Thanks a lot 🙂

Cannot get presence informations even thought developer portal switches are enabled discord.js

I have my code here :

// ...
    run: (client,message,args) =>{
        let member = message.member
        console.log(member.presence) // null
        if(!member.presence) return message.say(`${n} - I cannot access **${member.nickname || member.user.tag}**'s presence.`)
        if(!member.presence.activities[0]) return message.reply(`${n} - No activity detected from `${member.user.tag} !``)
        message.reply('Informations logged on the console.')
        console.log(member.presence)
    }

I keep having my bot sending this :

No activity detected

After having checked if other people got the same issue I only saw people who didn’t activated the following check boxes :

The switches

The thing is I already did and no matter how many times I rerun my bot, member.presence keeps being null and I can’t understand why.

Function inside event listener won’t run

How do I get the function computerChoice() to run when I click on the strawberryButton which has an addEventListener? At the moment nothing happens when I click on strawberryButton

<div class="fruits"> 
    <div class="strawberry">
        <img class="strawberry-button" src="strawberry1.png" height=250px></div>
    <div class="orange">
        <img class="orange-button" src="orange.png" height=250px width=250px></div>
    <div class="pineapple">
        <img class="pineapple-button" src="pineapple.png" height=250px width=250px></div>
    <div class="pear">
        <img class="pear-button" src="pear.png" height=250px width=250px></div>
</div>

my JS

// Initialize everything to zero
let score = 0;
let rounds = 0;

const strawberryButton = document.querySelector(".strawberry-button");
const orangeButton = document.querySelector(".orange-button");
const pearButton = document.querySelector(".pear-button");
const pineappleButton = document.querySelector(".pineapple-button");
const score_div = document.querySelector(".score");
const userChoice_div = document.querySelector(".user-choice");
const computerChoice_div = document.querySelector(".computer-choice");

    function computerChoice(){
        const fruitSelection = ["orange", "strawberry", "pear", "pineapple"];
        const pickFruit = fruitSelection[Math.floor(Math.random() * 4)];
        return pickFruit;

    }

strawberryButton.addEventListener('click', computerChoice)

Finding Palindrome Number with js but problem with negative numbers

/**
 * @param {number} x
 * @return {boolean}
 */
var isPalindrome = function(x) {
    
  let a, b, c = 0;
    a = x%10;
    x=x-a;
    b= x/10;
    c= b%10;
    let d = b-c;
    let f = d/10;
    let g = (a*100) + (c*10) + f;
    if (g==x && x>0)
        return "true";
    else 
        return "false";
};

when the number is negative its not saying false, it says true instead. But i added x>0 condition. What’s the problem? And btw my code also doesn’t look good maybe it’s not a good way to solve the palindrome problem. And also i am not so sure if its working with numbers with more than 3 digits.

How to find factorial using a function with constraints in JavaScript

I am trying to find the factorial of an integer using a function with the following constraint

1<=N<=10

Below is my code but when I execute it I am receiving NaN! Can you please explain and show me where is my mistake. Much appreciated!

const factorial = function (n) {
  if (n >= 1 && n <= 10) {
    return n * factorial(n - 1);
  }
};

console.log(factorial(5));

Uncaught TypeError: Cannot read properties of undefined (reading ‘func’)

I am trying to fire up a legacy React v14 project and all I did was refactor a bit the index.js file, the root level index.js file to look like this:

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import { Router, Route, IndexRoute, browserHistory } from "react-router";

import App from "./components/app";
import reducers from "./reducers";

const createStoreWithMiddleware = applyMiddleware()(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <Router history={browserHistory}>
      <Route path='/' component={App}></Route>
    </Router>
  </Provider>,
  document.querySelector(".container")
);

And as a result I get an error in console that says:

Uncaught TypeError: Cannot read properties of undefined (reading
‘func’)

Clear value for searchable dropdown when no results found using typeahead

I have three fields Name, Dept. and Title where Name is a Searchable dropdown field. Dept. and Title are read only fields. I want to be able to clear the fields Dept. and Title when no results are returned for Name.

First I selected test,test from the dropdown list under Name. After I select it, then the Dept. and Title show up.

enter image description here

If I change the Name and get no result (None found), I want to clear Dept and Title fields. How can I do that?

enter image description here

Here is my code

 <script>

                var Speakers = new Bloodhound({
                    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
                    queryTokenizer: Bloodhound.tokenizers.whitespace,
                    limit: 10,
                    remote: {
                        url: '/AJAX/searchspeakers?q=%QUERY&searchType=Speakers',
                        rateLimitWait: 250,
                        ajax: { cache: false }
                    }
                });

            Speakers.initialize();

                var setupTypeAhead = function (target) {

                    $(target + '_Name').typeahead(null, {
                        name: 'Speakers',
                        display: 'Name',
                        source: Speakers.ttAdapter(),
                        minLength: 3,
                        highlight: true,
                        templates: {
                            empty: [
                                '<div class="empty-message">',
                                'None found...',
                                '</div>'
                            ].join('n'),
                            suggestion: Handlebars.compile('<div><strong>{{Name}}</strong><br>{{Extra}}</div>')
                        }
                    }).on('typeahead:selected typeahead:autocompleted', function (obj, selected, name) {
                        $(target + '_Name').val(selected.Contact.Name);
                        $(target + '_Dept').val(selected.Contact.Dept);
                        $(target + '_Title').val(selected.Contact.Title);
                    }).off('blur', function () {
                        $this('close');
                    });
                }


        </script>

how do I add a object title when adding a object to another object

I am trying to add a object title of Nicaragua to my another object in javascript. so it will describe the propertys of nicaragua. How would I do that. I am using the object.assign method but because it is only a variable I am assigning as a 3rd property it will not label my property’s of Nicaragua as being a Nicaraguan object.

Example

`{
buenosAires: {
depth: ‘400 meters’,
annualBudget: 1000000,
specimens: [ ‘Dilophosaurus’, ‘Brachiosaurus’ ]
},

mexico: {
depth: ‘350 meters’,
annualBudget: 900000,
specimens: [ ‘Gallimimus’, ‘Parasaurolophus’ ]
},

depth: ‘200 meters’,
annualBudget: 1500000,
specimens: [
‘Tyrannosaurus Rex’,
‘Stegosaurous’,
‘Triceratops’,
‘Velociraptor’,
‘T rex’
]
}


As you can see the last properties do not have a object label of nicaragua, but they were sucessfully joined. Here is the code I was working with to create the above below. 

const nicaragua = {
depth: ‘200 meters’,
annualBudget: 1500000,
specimens: [
‘Tyrannosaurus Rex’,
‘Stegosaurous’,
‘Triceratops’,
‘Velociraptor’,
],
};

const hammondsMines = {
buenosAires: {
depth: ‘400 meters’,
annualBudget: 1000000,
specimens: [‘Dilophosaurus’, ‘Brachiosaurus’],
},
mexico: {
depth: ‘350 meters’,
annualBudget: 900000,
specimens: [‘Gallimimus’, ‘Parasaurolophus’],
},
};




Object.assign(hammondsMines,nicaragua)

console.log(hammondsMines)









MUI Module not found: Can’t resolve ‘@emotion/react’

Tried this, doesn’t work

Using latest MUI

Module not found: Can't resolve '@emotion/react'

Ok install it then..
npm i @emotion/react @emotion/styled -s

Package showing up in package-lock.json.

"node_modules/@emotion/react": {
      "version": "11.7.1",
      ........

Should be good to go..


Start up the server..
npm start

Once again..
Module not found: Can't resolve '@emotion/react'

Koa server– How to pass data in the server between middlewares so I can pass it to the front end

In my server, I have the following set up to grab the current logged-in user data:

  const server = new Koa();
  const router = new Router();
  server.keys = [Shopify.Context.API_SECRET_KEY];
  server.use(
    createShopifyAuth({
      async afterAuth(ctx) {
        // Access token and shop available in ctx.state.shopify
        const { shop, accessToken, scope } = ctx.state.shopify;

  const client = new Shopify.Clients.Rest(shop, accessToken);
        const data = await client.get({
          path: 'users/current',
        });

I am correctly getting the data but I would like to pass it to the front end.
I’ve tried storing the data in a global variable, I’ve tried storing the data in app.context and I’ve tried storing the data in ctx.state.

My idea is that I’d be able to grab the data and place it in the following so that I can make a fetch request to this /user endpoint:

router.get('/user', (ctx,next) => {
  next();
  console.log('check for ctx.state: ', ctx.state);
})
  

At the end of the day, I need access to the shop and accessToken from the Auth function which is why I’d need to pass the data instead of making the data request in the router.get function.
I haven’t worked with Koa before so any help would be greatly appreciated. Thank you!