Unable to copy credentials to clipboard in Rails app – JavaScript clipboard API issues

Problem:

I’m building a Ruby on Rails application that manages user credentials and allows users to share them securely. However, I’m running into an issue where I am unable to copy the credentials to the clipboard using JavaScript’s Clipboard API. I can generate a link (https only) to share the credentials, but the actual copying to the clipboard doesn’t seem to work. Setup:

Rails Version: 7.2.2
Ruby Version: 3.2.6
JavaScript: Using the Clipboard API to copy credentials to the clipboard.
Browser: Firefox.

Localhost

Clipboard API usage:
This code “works”, but it’s not what i want it to do, i just want to copy the credentials to the clipboard (later when it works, i will be doing some changes). But it just works if i do it with an URL.
I have a button in my app that, when clicked, generates a URL (just tested whatever website) with the credentials and attempts to copy this URL to the clipboard. Here’s the JavaScript I am using:

document.querySelectorAll(".share-credentials-btn").forEach(function(button) {
  button.addEventListener("click", function() {
    const unlocked = button.getAttribute("data-unlocked") === 'true';
    if (unlocked) {
      const username = button.getAttribute("data-username");
      const password = button.getAttribute("data-password");

      // Generate the URL to share credentials
      const passwordPusherLink = `https://www.passwordstore.com/push?username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`;
      
      // Try to copy the URL to the clipboard
      navigator.clipboard.writeText(passwordPusherLink).then(function() {
        alert("Credentials copied to clipboard!");
      }).catch(function(error) {
        alert("Error copying credentials: " + error);
      });

      // Optionally open the link in a new window
      window.open(passwordPusherLink, "_blank");
    } else {
      alert("Unlock the credentials to share them.");
    }
  });
});

The issue: The function to copy text to the clipboard works in some cases, but not in others. Sometimes the text doesn’t get copied, and I receive an error message in the catch block. I’m also unsure if there’s any condition under which the Clipboard API will fail (e.g., browser security settings, pop-up blockers, etc.

What I’m trying to achieve: I need a reliable way to copy credentials to the clipboard when the user clicks a button. I want the credentials to be copied securely and seamlessly without requiring additional user input (like pressing CTRL+C). So, i am new in rails and js, making a new project to learn and would appreciate some help. Thanks.

Angular: Empty input condition for string validation not working

The following functions are defined in an Angular component:

    handleInput(event) {
        // Validate the input
        if (event.target.value.length >= 8) {
            this.validate(event.target.value);
        }
    }
    // Validation logic for provider NG_VALIDATORS will
    // Logic for NG_VALIDATORS provider, returns validation result to parent form
    /** @internal */
    validate(control) {
        const value = control.value || control;
        if (this.required && value.replace(/s+/g, '').length === 0) {
            this.hasError = this.control.touched || this.control.dirty;
            this.errorText = [{ message: this.requiredErrorMessage }];
            return this.required ? { required: 'date required' } : null;
        }
        if (!value) {
            this.hasError = false;
            return null;
        }
        const [day, month, year] = value.split('.').map(Number);
        if (day && month && year && value.length === 10) {
            const date = new Date(year, month - 1, day);
            const isDateValid = !isNaN(date.getTime()) && date.getFullYear() === year && date.getMonth() + 1 === month && date.getDate() === day;
            this.hasError = !isDateValid || date > this.maxDate || date < this.minDate;
            if (this.hasError) {
                this.hasError = true;
                this.errorText = [{ message: this.validationErrorMessage }];
                return { invalid: 'date invalid' };
            }
        }
        this.hasError = false;
        return null;
    }

This is the corresponding custom input field:


    <input
      #input
      type="text"
      mask="00.00.0000"
      autocomplete="off"
      (input)="handleInput($event)"
      [(ngModel)]="value"
    />


The input field will add with ngx-mask a mask for a date field in DD.MM.YYYY format.

Problem:

When the component is rendered, the following error is thrown:

ERROR TypeError: value.split is not a function

For this line of code: const [day, month, year] = value.split('.').map(Number);

I already tried to fix it with

if (!value) {
            this.hasError = false;
            return null;
        }

The error is shown when the component is rendered of if a string was entered in the input field and then the input has been deleted (empty input field).

Toggle CSS onmouseover – WordPress Menu

I have a wordpress menu in which every links a custom class.

Onmouseover, I’d like this class to change the css of another element in the page.

I tried without success:

$('.menuclass').onmouseover(function () {$('.other-element').toggleClass("hover");});

I might go the wrong way about it, do you guys have any idea?

Validate XML message coming from DB query in PDI

I am retrieving XML messages that are stored in a database via query. Before sending them to a “Get Data from XML” step, I want to make sure that the XMLs are well formatted.

There is a step on Job level that performs that check but in order to use it I would have to write every message to a file first which I do not want.

Is there another way to validate an XML within the transformation? I was looking at using the Modified JavaScript value step but all the examples I found on the web to do that seem to refer to a JS version higher than 3.0 (which is currently used by PDI).

Is there any working example for PDI that truly works?

Problem with loading JSON file into IndexedDB through javascript

So I need to load this file into IndexedDB called Admin.json and these are the contents of it:

[
 {"username": "sheilah", "password": "sheilah123"},
 {"username": "joella", "password": "joella123"},
 {"username": "roselin", "password": "roselin123"},
 {"username": "rozalin", "password": "rozalin123"},
 {"username": "melisse", "password": "melisse123"},
 {"username": "berny", "password": "berny123"},
 {"username": "bink", "password": "bink123"},
 {"username": "vaughn", "password": "vaughn123"},
 {"username": "elmira", "password": "elmira123"},
 {"username": "roddie", "password": "roddie123"}
]

So I have written this code for it in my js file:

let db;

function openDatabase() {
const request = indexedDB.open('HospitalDB', 1); // Open database with version 1

request.onupgradeneeded = function(event) {
    db = event.target.result;
    
    // Create an object store for 'admins' if it doesn't exist
    if (!db.objectStoreNames.contains('admins')) {
        const store = db.createObjectStore('admins', { keyPath: 'username' });  // 'username' as the unique key
        store.createIndex('password', 'password', { unique: false }); // Create an index on 'password'
    }
    console.log("Database created/updated successfully!");

// Create an object store for 'patients' if it doesn't exist
if (!db.objectStoreNames.contains('patients')) {
    db.createObjectStore('patients', { keyPath: 'id' });
}

// Create an object store for 'medicines' if it doesn't exist
if (!db.objectStoreNames.contains('medicines')) {
    db.createObjectStore('medicines', { keyPath: 'id' });
}
}

request.onsuccess = function(event) {
    db = event.target.result;
    console.log("Database opened successfully!");
    
    // Call the function to load and insert the admin data
    loadAndInsertAdminData();
    loadAndInsertPatientData();
    loadAndInsertMedicineData();
}
// Function to load and insert the admin data into the IndexedDB

async function loadAndInsertAdminData() {
try {
    // Fetch the admin data from the local JSON file
    const response = await fetch('http://localhost:8000/files/Admin.json');
    const adminData = await response.json();

    // Insert the admin data into the IndexedDB
    const transaction = db.transaction(['admins'], 'readwrite');
    const store = transaction.objectStore('admins');

    adminData.forEach(admin => {
        const request = store.add(admin);
        request.onsuccess = () => {
            console.log(`Added admin ${admin.username} to the database.`);
        };
        request.onerror = (event) => {
            console.error("Error adding admin:", event.target.error);
        };
    });

    transaction.oncomplete = function() {
        console.log("All admin data added to the database.");
    };

    transaction.onerror = function(event) {
        console.error("Transaction error:", event.target.error);
    };
} catch (error) {
    console.error("Error fetching or inserting admin data:", error);
}
} .

The admin file is loading onto the DB but I’m still getting an error saying “error adding admin” along with the transaction error. I’ve used similar code for my other 2 json files Medicines.json and Patients.json and those files arent even showing up on the DB when i go to the developer tools from inspect element on my website. I’m getting the same transaction errors and error fetching the file for those files too. For context I’m running the localhost:8000 from my project file directory with the cmd command: python -m http.server 8000 . What’s the problem here?

Theme Not Loading on Page Load but Works on Radio Button Selection

I’m purely a beginner and this is for my project in one of my majors. I’m trying to implement a theme-switching feature on one of my subpages (Article1.html) using JavaScript, where users can select themes (Dark Modern, Pink Pastel, Windows XP) via radio buttons in a pop-up menu. The theme should load immediately when the page loads if it was previously saved, but it only loads after selecting a theme from the menu. I can’t see any css and it’s just plain html when I open the index.html (parent page/home).

Here’s what I have:

  1. JavaScript function (setTheme) that changes the CSS file, and header image based on the selected theme.
  2. Radio button listeners that call setTheme and save the selection to localStorage when a theme is chosen.
  3. Page load function that retrieves the saved theme from localStorage and applies it via setTheme, which I expect to apply the theme immediately on load.

I appreciate any help. Thank you.

Code for HTML:

<!--Control Panel-->
        <div class="controlPanel">
            <button class="arrangement" onclick="openMenu('arrangementMenu')">Arrangement</button>
            <button class="order" onclick="openMenu('orderMenu')">Order</button>
            <button class="themes" onclick="openMenu('themesMenu')">Themes</button>
        </div> <!--controlPanel-->

        <!-- Overlay -->
        <div class="overlay" id="overlay" onclick="closeMenu()"></div>

                <!-- Arrangement Menu -->
                <div id="arrangementMenu" class="popupMenu">
                    <button class="closeBtn" onclick="closeMenu()">X</button>
                    <h3>Arrangement</h3>
                    <hr>
                    <div class="notAvailable">
                        <p>This feature is not available for this page.</p>
                        <p>Go <a href="../index.html">back to home.</a></p> 
                    </div>
                </div> <!-- arrangementMenu -->

                <div id="orderMenu" class="popupMenu">
                    <button class="closeBtn" onclick="closeMenu()">X</button>
                    <h3>Order</h3>
                    <hr>
                    <div class="notAvailable">
                        <p>This feature is not available for this page.</p>
                        <p>Go <a href="../index.html">back to home.</a></p>
                    </div>
                </div>
                <!-- orderMenu -->
                
                <!-- Themes Menu -->
                <div id="themesMenu" class="popupMenu">
                    <button class="closeBtn" onclick="closeMenu()">X</button>
                    <h3>Theme:</h3>
                    <hr>
                    <div class="radio-group">
                        <label><input type="radio" name="theme" value="astyle - dark modern.css" onclick="setTheme('astyle - dark modern.css')">Dark Modern</label>
                        <hr>
                        <label><input type="radio" name="theme" value="astyle - pink pastel.css" onclick="setTheme('astyle - pink pastel.css')">Pink Pastel</label>
                        <hr>
                        <label><input type="radio" name="theme" value="astyle - windows xp.css" onclick="setTheme('astyle - windows xp.css')">Windows XP</label>
                    </div>
                    <button onclick="saveTheme()" class="closeBtn">OK</button>
                </div> <!-- themesMenu -->

Code for Javascript:

// Function to open a menu
function openMenu(menuId) {
    console.log("Opening menu:", menuId);
    document.getElementById("overlay").style.display = "block";
    document.querySelectorAll(".popupMenu").forEach(menu => {
        menu.style.display = "none";
    });
    // Takes the ID of menu and plugs in to this getElementById
    document.getElementById(menuId).style.display = "block";
}

// Function to close a menu
function closeMenu() {
    document.getElementById("overlay").style.display = "none";
    document.querySelectorAll(".popupMenu").forEach(menu => {
        menu.style.display = "none";
    });
}

// Function to switch themes based on radio button selection and save to local storage
function setTheme(sheet) {
    var stylesheet = document.getElementById('articleTheme');
    stylesheet.setAttribute('href', sheet);
    localStorage.setItem('cssTemplate', sheet);

    var header = document.getElementById("header");
    
    if (sheet === "astyle - dark modern.css") {
        header.src = "../images/dark modern header.png";
    } else if (sheet === "astyle - pink pastel.css") {
        header.src = "../images/pink pastel header.gif";
    } else if (sheet === "astyle - windows xp.css") {
        header.src = "../images/windows xp header.gif";
    }    
}

window.addEventListener("load", function() {
    var themeStyle = localStorage.getItem('cssTemplate') || 'astyle - dark modern.css';
    setTheme(themeStyle);
});

cypress error no internet access url behind proxy

cypress throwing an error for no internet access

cy.visit("URL");

Socks5.pac file

function FindProxyForURL(url, host)
{
   if (isInNet(host, "some IPV4 address ", "Some IPV4 Address"))
   return "SOCKS5 localhost:1080; SOCKS5 localhost:8080";
}

Cypress configuraiton file

// cypress.config.js
const { defineConfig } = require('cypress');

module.exports = defineConfig({
  chromeWebSecurity: false,
  env: {
    HTTP_PROXY: 'socks5://localhost:1080',
    // https_proxy: 'socks5://<proxy_host>:<proxy_port>',
    HTTPS_PROXY: 'socks5://localhost:1080',
  },
  e2e: {
    setupNodeEvents(on, config) {
      // Add any custom setup for the e2e tests if needed
      return config;
    },
  },
});

Unable to open web url which under the proxy and secure certificate.

Why does `window.addEventListener(“error”, …)` sometimes give “Script error.” with no other details?

(I initially thought this was just a Chrome bug, but I’ve tested in Firefox and it has similar weird behavior, and even uses the exact same “Script error.” string in the event.message, so I’m wondering whether this is a spec-related issue.)

My intuition with the code below is of course that each of the tests (where I purposely input an invalid value into a constructor) should produce the same ErrorEvent (just with different line numbers and stuff) in the window.addEventListener("error", ...) handler, but as noted in the comments of this code block, they produce different behavior.

<script>
  window.addEventListener("error", function(e) {
    console.error("window error handler:", e);
  })
</script>

<!-- Note: This is just an immutable snapshot of https://codemirror.net/codemirror.js and note that the txt extension doesn't affect this issue - it occurs with js extension too. The txt was just because github doesn't allow uploading js files. -->
<script src="https://github.com/user-attachments/files/17729754/codemirror6-november-13-2024.txt"></script>

<script>
  let { EditorView } = CM["@codemirror/view"];
</script>

<script>
  new EditorView(null); // Example 1: just "Script error."
</script>

<script type="module">
  new EditorView(null); // Example 2: just "Script error."
</script>

<script type="module">
  await new Promise(r => setTimeout(r, 10));
  new EditorView(null); // Example 3: just "Script error."
</script>

<script>
  (async function() {
    new EditorView(null); // Example 4: no window error event at all??
  })();
</script>

<script type="module">
  let { EditorView } = await import("https://esm.sh/@codemirror/[email protected]");
  new EditorView(null); // Example 5: ✅ produces error event with the actual error attached 
</script>


<!-- note: this uses a data url, but i tested using an actual server to server this file and it's the same result -->
<script src="data:text/plain,window.foo=function(a){a.b.c}"></script>
<script>
  foo(1); // Example 6: ✅ produces error event with the actual error attached 
  // caveat: in firefox, specifically, this data URL version gives "Script error.", but substituting it with a server url version results in the same behavior as chrome.
  // chrome gives the 'correct' behavior for both cases.
</script>

Notes:

  • I initially thought it had something to do with module scripts, but the last example shows that’s not the cause.
  • I thought maybe Example 4 had something to do with needing a window.addEventListener("unhandledrejection", ...) handler, but I tried that and it didn’t receive any events.
  • The ErrorEvent also includes the filename property, which gives the script that caused it (but includes no line number, stack, etc.)

Extra Context:

I’m building a developer tool which hooks into the error events on the page to help the developer understand the cause/source of the error. I don’t control the code on the page, so I need to be able to get the error details without re-writing the code.

Hence “you could just avoid writing your code/imports in XYZ form” is unfortunately not a solution for me.

AJAX Request Not Working on Live Server, But Works Locally – Any Ideas?

I’m working on a website that uses AJAX to fetch data from an API, and everything works perfectly on my local development server. However, when I upload it to the live server, the AJAX request fails without any clear error message. I’ve double-checked the API endpoint, and it’s accessible from the live server, so I’m not sure what’s going wrong.

Here’s what I’ve tried:

Confirmed that the API URL is correct and accessible from the live server.
Checked the browser console, but I only see a generic “Network Error” without much detail.
Ensured CORS headers are set correctly on the API side.
Could there be server settings or configuration differences that would cause AJAX to fail only on the live environment? Or are there any common troubleshooting steps for AJAX issues on live servers? Any help would be greatly appreciated!

Thanks!

Confirmed that the API URL is correct and accessible from the live server.
Checked the browser console, but I only see a generic “Network Error” without much detail.
Ensured CORS headers are set correctly on the API side.

React Native Warning: A props object containing a “key” prop is being spread into JSX with BottomTab.Navigator and react-native-paper

I’m encountering the following warning in my React Native project when using BottomTab.Navigator from @react-navigation/bottom-tabs and BottomNavigation.Bar from react-native-paper

Error

Warning: A props object containing a "key" prop is being spread into JSX: 
<Touchable {...props} />
React keys must be passed directly to JSX without using spread.

Here’s a code snippet of how I have set up my bottom tab navigation:

function AppNav({ routes }) {
  const renderTabBar = ({ navigation, state, descriptors, insets }) => {
    const navigationBarProps = {
      version: 3,
      style: {
        backgroundColor: "#212529",
      },
      activeColor: "orange",
      inactiveColor: "lightgrey",
      shifting: false,
      navigationState: state,
      safeAreaInsets: insets,
      onTabPress: ({ route, preventDefault }) => {
        const event = navigation.emit({
          type: "tabPress",
          target: route.key,
          canPreventDefault: true,
        });

        if (event.defaultPrevented) {
          preventDefault();
        } else {
          navigation.dispatch({
            ...CommonActions.navigate(route.name, route.params),
            target: state.key,
          });
        }
      },
      renderIcon: ({ route, focused }) => {
        const { options } = descriptors[route.key];
        return options.tabBarIcon ? options.tabBarIcon({ focused, size: 24 }) : null;
      },
      getLabelText: ({ route }) => {
        const { options } = descriptors[route.key];
        return options.tabBarLabel ?? route.name;
      },
    };

    return <BottomNavigation.Bar {...navigationBarProps} />;
  };

  return (
    <BottomTab.Navigator
      screenOptions={{ headerShown: false }}
      tabBar={renderTabBar}
    >
      {routes?.map((route) => (
        <BottomTab.Screen
          key={route.key}
          name={route.name}
          component={route.component}
          options={{
            title: route.name,
            tabBarIcon: ({ size, focused }) => (
              <MaterialCommunityIcons
                name={focused ? route.icon_focused : route.icon_default}
                color={focused ? "orange" : "#fafafa"}
                size={size}
              />
            ),
          }}
        />
      ))}
    </BottomTab.Navigator>
  );
}

This happened when i upgraded my dependencies. Here are my current package versions:

    "react": "18.3.1",
    "react-native": "0.76.1",
    "expo": "^52.0.4",
    "@react-navigation/bottom-tabs": "^6.5.19",
    "@react-navigation/drawer": "^6.6.14",
    "@react-navigation/native": "^6.1.16",
    "@react-navigation/native-stack": "^6.9.25",

How to log the version of my Nuxt app on server startup?

I want to write out a log line that reads “started version 0.4.0” when I start up the server, where the version is taken from the package.json file.

I defined a module and I’m passing it the version from the nuxt.config.ts file like so:

import pkg from './package.json'

export default defineNuxtConfig({
//...
  modules: [
//...
    ['~/modules/server-startup-log', { version: pkg.version }]
  ]
})

The module’s code is:

import { defineNuxtModule } from '@nuxt/kit'

export default defineNuxtModule({
    setup(options) {
        console.log(`Started version ${options.version}`);
    }
})

This only works if I run the server in dev mode, but after I build the
app it no longer prints the line on start up? Why is that? How can I get
this line to print after building as well?

how to change the order of inputs in this extension app to make the newest lead at the top instead of the bottom

As you can see if u tried the code and save an input in the app it will be save in a top to bottom order and i want it to be from bottom to top order, here is the whole code and if you want the html and css code I will give it to you

let myLeads = []
const inputEl = document.getElementById("input-el")
const inputBtn = document.getElementById("input-btn")
const ulEl = document.getElementById("ul-el")
const deleteBtn = document.getElementById("delete-btn")
const leadsFromLocalStorage = JSON.parse( localStorage.getItem("myLeads") )
const tabBtn = document.getElementById("tab-btn")

if (leadsFromLocalStorage) {
    myLeads = leadsFromLocalStorage
    render(myLeads)
}

tabBtn.addEventListener("click", function(){    
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        myLeads.push(tabs[0].url)
        localStorage.setItem("myLeads", JSON.stringify(myLeads) )
        render(myLeads)
    }) 
})

function render(leads) {
    let listItems = ""
    for (let i = 0; i < leads.length; i++) {
        listItems += `
            <li>
                <a target='_blank' href='${leads[i]}'>
                    ${leads[i]}
                </a>
            </li>
        `
    }
    ulEl.innerHTML = listItems
}

deleteBtn.addEventListener("dblclick", function() {
    localStorage.clear()
    myLeads = []
    render(myLeads)
})

inputBtn.addEventListener("click", function() {
    myLeads.push(inputEl.value)
    inputEl.value = ""
    localStorage.setItem("myLeads", JSON.stringify(myLeads) )
    render(myLeads)
})

i tried to reverse the order in the render function but it didnt work as expected.

Cookie-Problem with Google Search widget and JavaScript/php

I am setting a cookie with javascript

document.cookie = "acceptCookies=1; expires=" + new Date(new Date().setFullYear(new Date().getFullYear() + 1)).toUTCString() + "; path=/; SameSite=Strict";

And it works just fine, but not when I open the site using the google search widget in android. In that case the cookie is lost every time I reopen it. SameSite=Lax has the same effect.

So I tried to reset it with php like this.

    if ($_COOKIE['acceptCookies'] != "2"){
        setcookie("acceptCookies", "2", ['expires' => time() + 3600*24*365, 'path' => '/', 'samesite' => 'Strict' ]);
    }

But the problem is not solved. Has anyone an idea how to solve this problem?

How to disable days of the week by periods?

I’m currently trying to add a date picker and disable certain days of the week, like Mondays, to prevent reservations on those days when the office is closed. I found the daysOfWeekDisabled parameter, and it works perfectly, but not specifically for this purpose:

$('#date_return').datetimepicker({
    language: "es",
    format: 'dd/mm/yyyy',
    autoclose: true,
    todayHighlight: true,
    showMeridian: false,
    startView: 2,
    minView: 2,
    maxView: 1,
    pickerPosition: "bottom-left",
    daysOfWeekDisabled: $scope.daysClosedInLocationOfReturn
});

This setup works as expected, but now I need to make it apply to specific periods. For example, from 12/31/2024 to 12/30/2025, and then another period from 12/31/2025 to 12/30/2026. Additionally, the days might change depending on the period.

I also searched online and found what I hoped would solve my problem:

isInvalidDate: function(date) {
    return date.day() === 0 || date.day() === 6;
}

With this function, I thought I could add more conditions to check additional criteria, like specific years or other conditions. However, it didn’t work as expected—it neither disabled the days of the week nor showed any error message. Is there any way I can block specific days within certain periods?