How can I show the multiple lines with textarea when I capture the Image with Html2Canvas?

I read many blocks and many articles. But not able to find any solution for when I capture the image with html2canvas line need to show multiple lines.

Currently, lines cut off when I capture the Image using html2canvas.
Here, My example:

//Html File Code
<div class="textarea-content" id="main-container">
  <textarea class="w-100 h-100 text-dark" rows="10" id="text-area">
A paragraph is defined as “a group of sentences or a single sentence that forms a unit” (Lunsford and Connors 116). Length and appearance do not determine whether a section in a paper is a paragraph. For instance, in some styles of writing, particularly journalistic styles, a paragraph can be just one sentence long.</textarea>
</div>

<button class="btn btn-primary" (click)="generatePDF()">PDF</button>
//Css File Code
p {
  font-family: Lato;
}

.textarea-content {
  overflow-y: auto;
  white-space: pre-wrap;
  color: #fff;
}
/* 
width: 400px;
height: 200px; 
*/
//TS File Code
  generatePDF() {
    let myPdf = document.getElementById('main-container');
    html2canvas(myPdf)
      .then((myPdfCanvas) => {
        var doc = new jsPDF('p', 'mm', 'a4');
        var myPdfImage = myPdfCanvas.toDataURL('image/png');
        doc.addImage(myPdfImage, 'PNG', 10, 10, 100, 50);
        return doc;
      })
      .then((doc) => doc.save('postres.pdf'));
  }

Can anyone guide me on how to show multiple lines when I capture the image with Canvas?

How to access iframe from chrome extension while evading cross origin error

In my chrome extension I’m trying to access some page contents. In some websites they use inner iframe elements. When I try to access them (using iframe.contentWindow.document or iframe.contentDocument), I get an error Uncaught DOMException: Blocked a frame with origin "https://example.com" from accessing a cross-origin frame. So is there a way to get to the inner elements of that iframe? Or do I need an extra permission or something in my extension?

Extension is v3

permissions ["storage", "tabs", "action", "gcm", "notifications"]

host_permissions ["https://*/"]

Unable to change dragging cursor style when dragging an object in Chrome using JavaScript and CSS

I’m trying to change the default dragging cursor style when dragging an object in Chrome using JavaScript and CSS. I have added the draggable attribute to the element and attached event listeners for dragstart and dragend events. In the dragstart event listener, I add a class called dragging to the element, which should change the cursor style to a pointer. However, the cursor style does not change as expected when I drag the element.

What I tried :

listElement.setAttribute("draggable", "true");

listElement.addEventListener("dragstart", () => {
    setTimeout(() => {
        listElement.classList.add("dragging");
    }, 0);
});

listElement.addEventListener("dragend", () => {
    listElement.classList.remove("dragging");
});
.list-name.dragging {
    opacity: 0 !important;
    cursor: pointer !important;
}

How to convert the `selectionRect` (point x and y coordinates ) of the electron`context-menu` params to a DOM Range?

How to convert the selectionRect of the context-menu params to a Range?

https://www.electronjs.org/docs/latest/api/web-contents#event-context-menu

https://developer.mozilla.org/en-US/docs/Web/API/Range

I’ve found this explanation: How to create a Range Object from a point (X and Y Coordinates)?

https://developer.mozilla.org/en-US/docs/Web/API/Document/caretPositionFromPoint

but with:

let range: Range = document.caretRangeFromPoint(selectionRect.x, selectionRect.y)
console.log("App_S-range: ", range)

I get :

selectionRect{
    "x": 675,
    "y": 205,
    "width": 69,
    "height": 92
}


App_S-range:  
Range 
collapsed: true
commonAncestorContainer: div.ant-space.css-dev-only-do-not-override-diro6f.ant-space-
horizontal.ant-space-align-center
endContainer: div.ant-space.css-dev-only-do-not-override-diro6f.ant-space-
horizontal.ant-space-align-center
endOffset: 0
startContainer: div.ant-space.css-dev-only-do-not-override-diro6f.ant-space-
horizontal.ant-space-align-center
startOffset: 0

And it shouldn’t be collapsed

How can I implement a custom JavaScript engine for specific hardware architecture, optimizing for performance and resource efficiency?

How can I implement a custom JavaScript engine for specific hardware architecture, optimizing for performance and resource efficiency?

he question aims to explore the process of creating a custom JavaScript engine optimized for a particular hardware architecture, with a focus on improving performance and resource efficiency. JavaScript engines are responsible for parsing, optimizing, and executing JavaScript code, converting it into machine-level instructions that can be understood and executed by the underlying hardware.

When dealing with specific hardware architectures, a generic JavaScript engine might not fully exploit the unique features and capabilities of the hardware, leading to suboptimal performance and resource utilization. To overcome this limitation, developers may consider building a custom JavaScript engine specifically tailored for the target hardware platform.

Patterns for default Properties

We inject a List of Components into a Card Component. This Card component has a GUI overlay, which allows Users to Choose the Component used and their Properties.

According to Dan Abramov FunctionalComponent.defaultProps will eventually be deprecated, which we used in our first prototype to bubble the required values upstream.

const Field = ({text}) => <div>{text}</div>
Field.defaultProps = {text: "Default Value"}

Our second Approach was adding a HOC receiving a callback from Card to provide the prop defaults this way.

const withGUI = (defaults, Component) => props => {
    const cb = props.onDefaultsChange
    useEffect(() => cb?.(defaults), [cb])
    return <Component {...props}/>
}

const Field = withGUI({text: "Default Value"}, ({text}) => <div>{text}</div>)

Our third approch simplified the HOC to

const withGUI = (defaults, Component) => {
    Component.gui_props = defaults
    return Component
}

Do the Approaches 1 and 3 differ enough to avoid interfering with the potential deprecation?

How to keep created elements on the web page after the page reload using javascript

I am trying to develop a web page for my little brother.It’s about a user interactive page for adding comments by the users.I am having trouble, after created the user comments with a for.Each function, in keeping those created comments on the web page after the page refresh.I know that i have to use “local.storage” function but i didn’t find any solution yet :’-(Can any good person help me please??Thank you!

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Comments</title>
  <link rel="stylesheet" href="css/reset.css">
  <link rel="stylesheet" href="css/nmComments.css">

</head>

<body>

  <header class="header">
    <a class="logo" href="#">
      <p>Comments page</p>
    </a>
    <button class="button--menu">
      <ion-icon class="menu--icon" name="menu"></ion-icon>
    </button>
  </header>

  <main>
    <div class="main">
      <form class="comment--form" action="#" id="form">
        <h1 class="interact">Interact with us!<br>Leave your comment here</h1>

        <div>
          <label for="comment--text">Your comment:</label><br>
          <textarea class="comment--box" type="text" required id="textarea" placeholder="Add your comment"
            maxlength="150"></textarea>
        </div>
        <button class="form--button" id="submit">Paste it</button>
      </form>
    </div>

    <h2 class="comments--h2">Comments</h2>
    <div id="comment--area" class="comment--area">
      <!-- <div class="client--box">
        <div id="name-box"></div>
      <div id="comment-box">
        </div>
        <button id="clear" class="hidden">
          &#128591;</button>
      </div> -->
    </div>
  </main>

  <footer>
    <div class="footer"></div>
  </footer>
  <script type="module" src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.esm.js"></script>
  <script nomodule src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.js"></script>

  <script language="Javascript">
const field = document.getElementById('textarea');

const submit = document.getElementById('submit');

const createComments = document.getElementById('comment--area');

const comments_arr = [];


submit.onclick = function(event){
    event.preventDefault();
    const content = field.value;
    if(content.length > 0){ // if there is content add the comment to the array
    
      comments_arr.push(content);

      // re-generate the comment html list

      display_comments();
      
      // reset the textArea and arrey contents
      comments_arr.length = 0;
      field.value = '';
      
    }
}

const display_comments = ()=> {
  let box = document.createElement('textarea');
  box.classList.add('comment--box');
  createComments.append(box);
  let list = '';
   comments_arr.forEach(comment =>  {
    list +=  comment;
  })

  box.append(list);
  box.innerHTML = list;
}
</script>
</body>

</html>

Component keeps re-rendering and I can’t figure out why

I’m fairly new to React and currently need to implement infinite scrolling. It’s working, however, every time new content is loaded the whole Feed component re-renders and I’ve been scratching my head over it for the whole day.

I’m using an Intersection Observer. Every time the scroll reaches the bottom of the page I use a custom hook to make a call loading 6 more elements.
This is the custom hook:

const usePosts = (pageNum = 1) => {
  const [results, setResults] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);
  const [error, setError] = useState({});
  const [hasNextPage, setHasNextPage] = useState(false);
  const { category } = useArticlesContext();

  useEffect(() => {
    setIsLoading(true);
    setIsError(false);
    setError({});

    const controller = new AbortController();
    const { signal } = controller;
    getPostsPageArticles(category, pageNum, { signal })
      .then((data) => {
        console.log(data);
        setResults((prev) => [...prev, ...data]);
        setHasNextPage(Boolean(data.length));
        setIsLoading(false);
      })
      .catch((e) => {
        setIsLoading(false);
        if (signal.aborted) return;
        setIsError(true);
        setError({ message: e.message });
      });

    return () => controller.abort();
  }, [pageNum, category]);
  useEffect(() => {
    setResults([]);
  }, [category]);

  return { isLoading, isError, error, results, hasNextPage };
};

And this is the component in question:

const Feed = () => {
  const [pageNum, setPageNum] = useState(1);

  const { isLoading, isError, error, results, hasNextPage } = usePosts(pageNum);
  const intObserver = useRef();

  const lastPostRef = useCallback(
    (post) => {
      if (isLoading) return;
      if (intObserver.current) intObserver.current.disconnect();

      intObserver.current = new IntersectionObserver((posts) => {
        if (posts[0].isIntersecting && hasNextPage) {
          console.log('We are near the last post');
          setPageNum((prev) => prev + 1);
        }
      });

      if (post) intObserver.current.observe(post);
    },
    [isLoading, hasNextPage],
  );

  if (isLoading) return <div>Loading...</div>;

  if (isError) return <div>Error: {error.message}</div>;

  const content = results.map((post, i) => {
    if (results.length === i + 1) {
      return <ArticleCard ref={lastPostRef} article={post} />;
    }
    return <ArticleCard article={post} />;
  });

  return (
    <div className="feed-container">
      {content}
      {isLoading && <p>Loading more posts...</p>}
    </div>
  );
};

The ArticleCard component in the content variable is this:

const ArticleCard = React.forwardRef(({ article }, ref) => {
  const articleCardBody = (
    <>
      <div className="article-card__title">
        <h2>{article.title}</h2>
      </div>

      <img src={article.img} alt="" className="article-card__img" />

      <div className="article-card__content">
        <p>{article.content}</p>
      </div>
    </>
  );

  const content = ref ? (
    <div className="article-card" ref={ref}>
      {articleCardBody}
    </div>
  ) : (
    <div className="article-card">{articleCardBody}</div>
  );
  return content;
});

Any help would be much appreciated, I’m losing my mind.

Thank you.

How to force Nuxt 2 middleware runs at least once on the client

on static site generation mode in Nuxt 2, global middleware (defined in nuxt.config) runs only on the server-side on the first page load. and will run on the client-side for further page navigations.

To get around this issue, I put my code inside of a Nuxt plugin:

plugins: [
  { src: '~/plugins/initializer.js', mode: 'client' }
   // other plugins
]

but this is not suitable for some scenarios, because plugins run after middleware.

I need to force a Middleware to run at least once on the client-side even dur
the first page load.

How Javascript selectors works [duplicate]

I have one HTML file And Two JS (jquery) files

first file function: to Request (select) some date from Database, and rewrite the element with the same class name.
second file function: to select element by class name, When element being Clicked on, there is some function does.

the Problem is: when the second file try to select elements with the class name, He can’t recognize the elements…!

I tried to solve:
I make $.getScript(“The second file”) to reload the second file to select the element again

Why this problem? and is there any solution to this problem?

Event Handling like a queue

So, basically, I want to do is:

  1. Get an Event from an event listener,
  2. handling that event,
  3. waiting for it to finish,
  4. and then pass to another in the queue,

so if I get like 15 an event 15 times, I don’t want to be handled all at the same time but more like event handle-await seconds event. I’ve tried like this to have one printed, then 5 seconds, then two with multiple clicks but what I’ve got was a lot of “one” at the same time and then a cascade of “two.”

document.addEventListener("click", async function(event) {
    if (!event.target.matches(".button-name"));
    console.log("one");
    await sleep(5000);
    console.log("two");
    event.preventDefault();
}, );

async function sleep(milliseconds) {
    return new Promise((resolve) =  > setTimeout(resolve, milliseconds));
}

Using variable in Javascript callback

I’m using the solr npm package to query a solr instance, and nightwatchjs as my test framework.

What I’m looking to do is access a random solr entry (which I will then extract info from) from my solr index.

The issue I’m having however, is getting this random entry.

The (example) solr index info I’m querying looks like this;

<?xml version="1.0" encoding="UTF-8"?>
<response>

    <lst name="responseHeader">
      <int name="status">0</int>
      <int name="QTime">0</int>
      <lst name="params">
        <str name="q">*:*</str>
        <str name="rows">1</str>
        <str name="facet">on</str>
        <str name="_">1688396679511</str>
      </lst>
    </lst>
    <result name="response" numFound="1867" start="0">
      <doc>
        <str name="CmsPageId">wp-13</str>
        <str name="UniqueIdentifier">ParkersReview-13</str>
        <str name="PageUrl">/penelope/mclaren/gt/coupe/review/</str>
        <str name="PrimarySection">cars</str>
        <int name="MakeId">77092</int>

So what I thought I could do was get the numFound value, randomize this value, and then use this in the callback.

And my solr query code looks like this;

exports.car_reviews_settings = function(solrWpProdClient, callback) {
    var seoCrawlPathLinksColourQuery = solrWpProdClient.createQuery()
    .q('*:*')
    .start(0)
    .rows(1)

    solrWpProdClient.search(seoCrawlPathLinksColourQuery,function(err,obj) {
        if(err) {
            callback(err,null);
            callback(err,obj.response.docs.length > 0);
        }
        else {
            var numberOfEntries = obj.response.numFound;
            console.log(numberOfEntries)
            var randomEntry = Math.floor(Math.random()* numberOfEntries)
            console.log(randomEntry)
            callback(null, obj.response.docs[`${randomEntry}`]);
            console.log(obj.response.docs[`${randomEntry}`])
        }
    });
};

The numFound is correctly displaying 1867. The random part is also working, as I get a random number for randomEntry.

However, I get an undefined for the obj.response.docs[`${randomEntry}`] part of the output.

Is obj.response.docs[`${randomEntry}`] the correct code for this, or is there something else I should be doing in order to get this working within the callback?

Thanks

nodejs problem sending the variable value to show controller

nodejs problem sending the variable value to show controller

— model–

class GloParameter {

    static findGlo(gloFunction, gloCode, gloValue, cb) {
        db.query(findGloParameterFCVActiveQuery, gloFunction, gloCode, gloValue, (err, res) => {
            if (err) {
                logger.error(err.message);
                cb(err, null);
                return;
            }
            if (res.length) {
                cb(null, res[0]);
                return;
            }
            cb({ kind: "not_found" }, null);
        })
    }

}

module.exports = GloParameter;

— controller–

exports.serviceX = (req, res) => {

    const xx1 = GloParameter.findGlo(['withdraw_money_time', 'withdraw_money_time', 'start'], (err, data) => {
        console.log('xxxxxxx', data[0].glo_info1)
        return data[0].glo_info1
    })

    res.status(200).send({
        status: 'success',
        data: xx1

    });

    return
}

Call Api

enter image description here

response API is parameter data : …..

Troubleshooting the display of results