Please help me automate clicks using a tampermonkey script [closed]

I need to automate clicking at certain coordinates on the screen every 10 milliseconds using a tampermonkey script. Please help me to write such a script. The script should automate clicking at certain coordinates on the screen every 10 milliseconds.

I tried writing a tampermonkey script that could automate clicking at certain coordinates on the screen every 10 milliseconds but it did not work.

How to Log a Window Object?

I need to obtain the values that services like Cloudflare check in the window object. Therefore, I am trying to capture which value is being requested from the window object whenever any value is requested. For example, when the window.screen.availWidth value is requested, I should log that the screen.availWidth value is being requested. This can be done using any tool like Puppeteer, Selenium, etc.

I tried to proxy the window object with the ‘new Proxy’ feature, but I was not successful. No logs appear in the console.

const originalWindow = window;

function logAccess(property) {
  console.trace(`Erişilen window özelliği: ${property}`);
}

window = new Proxy(originalWindow, {
  get: function(target, property) {
    logAccess(property);
    return target[property];
  }
});

Running Javascript in php page 1 that shows next array value every second in php page 1; need array values shown in real-time in php page 2 also

Sorry for the long title.

::: WHAT I DID ::::

I added javascript in php page 1 which we will call “test1.php”. There is an array with 10 values in the javascript. When test1.php is opened, the javascript runs, showing the next array value every second in test1.php in a div called “h1”.

::: WHAT I NEED :::

I need to be able to open test1.php which starts the javascript, causing the next array value to show every second in a div called “h1” in test1.php. There is a second php page we’ll call “test2.php”. Now test1.php is open and the javascript is running showing the next arrary value in a div called “h1” in test1.php. When I open test2.php, I need test2.php to also show each array value from test1.php every second in real-time and if I refresh test2.php, I should still see each array value from the javascript running in test1.php showing in test2.php in real-time. Whenever I open test1.php and then open test2.php, both pages (test1.php and test2.php) should always show the exact same array values every second no matter how many times I refresh test2.php. The javascript only stops when I close test1.php. I was able to create a javascript in test1.php that shows the next array value every second in a div called “h1” in test1.php. I was not able to make the array values show in test2.php at all.

Extra info: Thank you to @HasanABLAK for bringing this to my attention. So test1.php will be open on my computer. And test2.php will be open on multiple computers in America and worldwide by different users. Yes, me and all users should see the same array values appearing at the same time regardless of our differing timezones (I see the array values in test1.php and they see the exact same array values in test2.php, all in real-time). Both php pages (test1.php and test2.php) are on the same server and under the same domain name, same website. The website is owned and operated by me.

:::: QUESTION ::::

How do I make each array value from test1.php show in test2.php in real-time with test2.php always showing the exact same array values appearing in test1.php no matter how many times I refresh test2.php? The javascript that shows the next array value every second in a div called “h1” in test1.php is shown below. Thank you!

<div id="h1"></div>
<script>
var dialog = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];

function changeText() {
  var timer = 0;
  for (let i = 0; i < dialog.length; i++) {
    setTimeout(() => document.getElementById('h1').innerHTML = dialog[i], timer);
    timer = timer + 1000;
  }
}

changeText();
</script>

Change CSS of the clicked element

Probably a silly question, but the basic way I learned how to change CSS of something on click is

var x = document.getElementById("id"); 
    x.style.height = "auto"; 

or whatever.

But say I want divs of a certain class to change CSS attributes when clicked. But not all at the same time, only the one I just clicked. Adding separate ID’s and functions to each of them seems irrational.

Thank you!

How get total in an array of object

I have this array, and i want to get the sum amount of each Order.item

[
{"OrderReceiverId":"6698eea782e24cc9d42eab7f",
"Order":{
 "CustomerId":"669aa55079cce2e96f9a7e69",
"CustomerName":"Erigbemi",
"Date":"2024/07/19",
"TrackingId":"43035",
"Status":"Processing",
"Amount":{"$numberInt":"25000"},
"Item":"Orange"
 }
}, {"OrderReceiverId":"6698eea782e24cc9d42eab7f",
"Order":{
 "CustomerId":"669aa55079cce2e96f96t77",
"CustomerName":"James",
"Date":"2024/07/19",
"TrackingId":"42335",
"Status":"Processing",
"Amount":{"$numberInt":"20000"},
"Item":"Rice"
 }, {"OrderReceiverId":"6698eea782e24cc9d42eab7f",
"Order":{
 "CustomerId":"669aa55079cce2e96f9a7e69",
"CustomerName":"Erigbemi",
"Date":"2024/07/19",
"TrackingId":"22235",
"Status":"Processing",
"Amount":{"$numberInt":"12000"},
"Item":"Rice"
 }
]

How do i get the total of each “Item”, something like this

“Rice”: 30000
“Tomatoes”: 15000

Error In Creating a Javascript For a Chat Bot, First Time

enter image description here

can anyone help me build a java script to automate my convo in a chat bot On Chrome? The website is IFreeChat

and what i would like to do is this :

send a message (“Hi I am X”) and then
another message “Hi I am Y” and then
the final message “Hi I am Z”

All 3 messages having a time interval / gap of 3 seconds

Can anyone help me build it?

The screenshot attached above is to define the classes

The text box class is (.writer-input)
The send chat (orange arrow to send the msg) class is (.writer-send)

This is my first time coding and i know basically 0% about it so please help me 🙂

enter image description here

I tried to write this code from YT but seems like i dont know what i am doing… 🙁

Display pdf in the browser received by JavaScript async

I have a Django app, I make a call from JS to ask for a pdf. Django view returns an HttpResponse of application/pdf

How do make JS to display the received application/pdf data as a pdf?

Django View

def pdf_generation(request):
    context = {}
    t = get_template('html_pdf.html')
    html_string = t.render(context)
    result = HTML(string=html_string)
    css = CSS('/static/css/pdf.css')
    pdf_in_memory = BytesIO()
    HTML(string=html_string).write_pdf(pdf_in_memory, stylesheets=[css])

    return HttpResponse(pdf_in_memory.getvalue(), content_type="application/pdf")

JS

async function getData_pdf() {
try {
    const response = await fetch('http://192.168.1.2:8000/pdf/'); 
    if (!response.ok) {
        throw new Error('Network response was not ok ' + response.statusText);
    }
    const data = await response.text();
    data.type('application/pdf');
    data.end(pdf, 'binary');
} catch (error) {
    console.error('There has been a problem with your fetch operation:', error);
}
};

Utilizing F# Fable Emit for passing String API Key not working

I have had some success working with F# Fable JS Interop for integrating with various 3rd party libraries like SignalR and LocalForage. However, I’m no expert, and just find myself learning here and there, and find myself stumped here in regards to trying to JS Interop with Stripe Elements. I’ve got a wider set of aspects working, but it is all built upon initializing an instance of Stripe within my ViewModel (this instance needs loaded when the ‘page’ first loads, but is supposed to be re-used (and not reloaded) in successive renders). It is all working correctly whenever I put in my key as a hard-code within the Emit attribute; however, I have not been able to get it such that I can correctly pass the key as a parameterized string. I figured that somebody may have some more experience or awareness with this, and so I will just try to highlight the particular approach. Any help is highly appreciated!

This all works correctly, when I call this and then use my IStripe instance within the ViewModel:

[<ImportDefault("@stripe/stripe-js")>]
[<Emit("Stripe('pk_test_TYooMQauvdEDq54NiTphI7jx')")>]
let initialize () : IStripe = jsNative

If I keep ImportDefault it no longer works, so I shifted this to ImportAll which no longer brings that error, but if I do this it tells me that I’m passing an Object instead of a string:

[<ImportAll("@stripe/stripe-js")>]
[<Emit("Stripe($0)")>]
let initializeByKey (key: string) : IStripe = jsNative

Thus, I do the following, and I don’t get the errors, but now it just get a 401 auth error from Stripe:

[<ImportAll("@stripe/stripe-js")>]
[<Emit("Stripe('$0')")>]
let initializeByKey (key: string) : IStripe = jsNative

This is the code that is calling the initializeByKey function:

let initViewModel () =
    { Stripe = StripeInstance.initializeByKey "pk_test_TYooMQauvdEDq54NiTphI7jx"
      CheckoutForm = init () }

This builds and runs correctly if I use the StripeInstance.initialize (), but not in this parameterized scenario. It seems like this is just something that I’m not doing correctly with the Emit attribute definition. I’m not really sure how to figure this out. I assume that somehow it is not passing the string correctly, or maybe adding the single-quote characters.

Astro page-load event is triggered in other page

I am a Astro begginer. I am using ViewTransitions. I am writting a website with several pages. In index.astro, I have a script which modifies some <a> elements. Therefore, I have written this:

    <script is:inline>
      console.log("script executed");
      document.addEventListener("astro:page-load", () => {
        console.log("page loaded");`

When I go to the root page of the website, everything works fine, I see that the script is executed and the page-load callback is executed. However, when I go to another page through the anchor, the callback (but not the script) is executed again, why? I don’t want that this happens.

I have tried removing the is:inline directive but does not change anything.

Await inside if block not waiting

I am loading some data from a DB table using sequelize and caching it in an in-memory object with a TTL so I don’t keep reading from the DB over and over again.

// ffm.ts
import { Op } from 'sequelize';
import { State } from 'src/db/models/geo/state';

export class FFMStates {
  private static lastRefreshed = new Date(0); // Initialize to start of epoch

  private static TTL = 60 * 60; // 1 hour

  public static DATA: Record<number, Array<string>>;

  public static async load() {
    FFMStates.lastRefreshed = new Date();
    const currentYear = FFMStates.lastRefreshed.getFullYear();

    const results = await State.findAll({
      where: {
        year: { [Op.gte]: currentYear - 2 }, // load 3 or 4 latest years
        ffm: true,
      },
      order: [
        ['year', 'ASC'],
        ['code', 'ASC'],
      ],
    });

    FFMStates.DATA = results.reduce((acc: Record<number, string[]>, state) => {
      if (!acc[state.year]) {
        acc[state.year] = [];
      }
      acc[state.year].push(state.code);
      return acc;
    }, {});
  }

  public static async get() {
    if ((new Date().getTime() - FFMStates.lastRefreshed.getTime()) / 1000 > FFMStates.TTL) {
      await FFMStates.load();
    }
    return FFMStates.DATA;
  }
}

I am then using this module as follows:

import { FFMStates } from 'src/constants/health/ffm';

const ffmStates = await FFMStates.get();
const currentYear = ffmStates[this.year]; // This throws an error the first time this code runs because ffmStates is undefined

I tried debugging this with console.log() statements. It seems that when FFMStates.get() is called the first time, my code starts to run FFMStates.load() but does not await it and immediately executes the next line after the if block and returns FFMStates.DATA which is undefined at this point. I am not sure why await FFMStates.load() does not wait.

Web Radio API costantly refreshing

so, I was trying to create a way via Laravel/Livewire to create some sort of Web Socket or otherwise continuous “communicate” with my API end-point. Basically I’m creating a Web Radio that allows me to listen to songs via AzuraCast. The API response gives me a lot of information including, “seconds_remaining”, “seconds_total”, “elapsed_second”. The fact is that I would like to be able to update my API, using a sort of Timer that, at the end of these “remaining_seconds”, my component has a refresh without “influencing” the Network Service too much.
I’m currently trying to update my component like this:

class TitleSong extends Component
{

    public $loading = true;

    public $TimePolling;
    public $elementToShow = '';
    public array $cachedData = [];
    public int $remainingTime;
    public $error = 'Something went wrong, try again...';
    public $audioURL;

    public function render()
    {


        return view('livewire.title-song');
    }


    public function mount(): void
    {
        $this->cachedData = Cache::get('song_data', [
            'title' => '',
            'artist' => '',
            'image' => '',
            'total_seconds' => 0,
            'seconds_elapsed' => 0,
            'seconds_remaining' => 0,
            'spotifyURL' => '',
            'audioURL' => '',
        ]);


/*         if ($this->cachedData) {
            $this->fetchSongData();
            $this->loading = false;
            $this->remainingTime = $this->cachedData['total_seconds'] - $this->cachedData['seconds_elapsed'];
        } */
    }

    public function fetchSongData()
    {
        try {
            $response = Http::get('http://138.197.88.112/api/proc/s/currently_playing');

            if (!$response->successful()) {
                throw new Exception('Failed to fetch song data.');
            }

            $data = $response->json()['song'];
            $this->TimePolling = $data['seconds_remaining'];
            // Update the component's state
            if ($data['title'] !== $this->cachedData['title'] || $data['artist'] !== $this->cachedData['artist']) {

                $this->cachedData = [
                    'title' => $data['title'],
                    'artist' => $data['artist'],
                    'image' => $data['art'],
                    'total_seconds' => $data['seconds_total'],
                    'seconds_elapsed' => $data['seconds_elapsed'],
                    'seconds_remaining' => $data['seconds_remaining'],
                    'spotifyURL' => $data['url'],
                    'audioURL' => 'https://stream.repeatradio.net/',
                ];


                $this->loading = false;

                // Cache the updated data
                Cache::put('song_data', $this->cachedData);
            }
        } catch (Throwable $th) {
            Log::error($th->getMessage());
            $this->handleFetchError();
        }
    }

    private function handleFetchError()
    {
        $this->error = 'Something went wrong. Please try again later.';
        $this->cachedData = [
            'title' => $this->error,
            'artist' => $this->error,
            'image' => '',
            'total_seconds' => 0,
            'seconds_elapsed' => 0,
            'audioURL' => '',
            'spotifyURL'=> '',
        ];
        $this->loading = false;
    }

Then in the view simply I display:

<div id="title-song" wire:poll.{{ $TimePolling }}s="fetchSongData">
    <!-- Actual Content -->
    <!-- IF THERE IS AN ERROR -->
    @if ($error && !$cachedData)
        @if ($elementToShow === 'songTitle')
            <h1 id="songTitle" style="font-weight: 600;" class="text-4xl text-red-600">{{ $error }}</h1>
        @elseif ($elementToShow === 'songArtist')
            <p id="songArtist" class="mt-2 ml-1 text-red-600" style="font-weight: 400; font-size: 15px">{{ $error }}
            </p>
        @elseif ($elementToShow === 'secondsTotal')
            <span id="secondsTotal" class="total-time">0</span>
        @elseif($elementToShow === 'songImage')
            <img id="artImage" class="text-center"
                style="position: absolute; left: 12%; top: 2%; border-radius:20px; z-index: 1; line-height:50%;"
                width="220px" height="200px" alt="No image found" />
        @elseif($elementToShow === 'audioURL')
            <audio src="" id="audio"></audio>
        @endif
    @else
        <!-- IF THERE IS NO ERROR -->
        @if ($elementToShow === 'songTitle')
            <h1 id="songTitle" style="color: var(--quaternary-color); font-weight: 600" class="text-4xl">
                {{ $cachedData['title'] }}</h1>
        @elseif ($elementToShow === 'songArtist')
            <p id="songArtist" class="mt-2 ml-1" style="color: var(--quinary-color); font-weight: 400; font-size: 15px">
                {{ $cachedData['artist'] }}</p>
        @elseif ($elementToShow === 'secondsTotal')
            <span id="secondsTotal"
                class="total-time">{{ substr($cachedData['total_seconds'], 0, 1) . ':' . substr($cachedData['seconds_elapsed'], 1, 2) }}</span>
        @elseif($elementToShow === 'songImage')
            <img id="artImage" class="spin"
                style="position: absolute; left: 12%; top: 2%; border-radius:20px; z-index: 1" width="220px"
                height="200px" src="{{ $cachedData['image'] }}" />
        @elseif($elementToShow === 'audioURL')
            <audio src="{{ $cachedData['audioURL'] }}" id="audio"></audio>
        @elseif($elementToShow === 'spotifyURL')
            <div class="spotify w-full">
                <svg width="24" height="24" fill="green" xmlns="http://www.w3.org/2000/svg" fill-rule="evenodd"
                    clip-rule="evenodd">
                    <path
                        d="M19.098 10.638c-3.868-2.297-10.248-2.508-13.941-1.387-.593.18-1.22-.155-1.399-.748-.18-.593.154-1.22.748-1.4 4.239-1.287 11.285-1.038 15.738 1.605.533.317.708 1.005.392 1.538-.316.533-1.005.709-1.538.392zm-.126 3.403c-.272.44-.847.578-1.287.308-3.225-1.982-8.142-2.557-11.958-1.399-.494.15-1.017-.129-1.167-.623-.149-.495.13-1.016.624-1.167 4.358-1.322 9.776-.682 13.48 1.595.44.27.578.847.308 1.286zm-1.469 3.267c-.215.354-.676.465-1.028.249-2.818-1.722-6.365-2.111-10.542-1.157-.402.092-.803-.16-.895-.562-.092-.403.159-.804.562-.896 4.571-1.045 8.492-.595 11.655 1.338.353.215.464.676.248 1.028zm-5.503-17.308c-6.627 0-12 5.373-12 12 0 6.628 5.373 12 12 12 6.628 0 12-5.372 12-12 0-6.627-5.372-12-12-12z" />
                </svg>
                <a target="_blank"
                    href="{{ $cachedData['spotifyURL'] }}">{{ Str::limit($cachedData['spotifyURL'], 20, '...') }}</a>
            </div>
        @endif
    @endif
</div>

This is kind of a solution, because wire:poll takes a “dynamic” value. But it crashes after a while and sometimes, not always, with a message of:

Maximum execution time of 60 seconds exceeded

I don’t have really more ideas for this. I tried in so many ways…

I tried to work with JavaScript but I cannot work with PHP variables and I cannot even do "setAttribute" for the parent div with wire:poll.
I tried to use a Queue of laravel, but the component since it’s a Livewire component it kinda broke the code.
Someone just told me to try to use, WebSocket Broadcasting Laravel.

Making BeEF shenanigans accessible to the internet with W3Spaces

I’ve recently discovered BeEF and its capabilities.
But I find it a little problematic that I’ve only been able to run the pages on my own system.

What I desire is that I want the BeEF page to be accessible by anyone with an internet connection.
I’m aware that i can simply use ngrok for this but I kinda wanna see if the spaces on w3schools . com can be used for this purpose or not?

I asked chatgpt and it said it can be used but i didnt understand the instructions it gave me, can anyone help ?

NOTES:

  1. This isn’t for any weird or illegal activities. The most evil thing i’d probably do is mess with my family (with permission ofc)
  2. i included the javascript tag cuz BeEF is said to work through Javascript
  3. I realize the question is very specific, but any help is appreciated :’)

Setting On in dropdown semantic ui don´t work

I’m trying in my dropdown, which already works, allowing it to only perform the search when the “Search” button is clicked.

I saw in the semantic Ui documentation that there is an “On” option that can help me with the click event

https://semantic-ui.com/modules/dropdown.html#/settings

I thought using: On: $(#myButton).click() could solve my problem but that doesn’t seem to be the case.

cshtml
<div id="idDrop" class="ui fluid search selection dropdown"">
<input class="search">
<i class="search icon" aria-hidden="true"></i>
</div>
<div>
<button class="ui button bgm-wine-bnb icon labeled" type="button" id="btnSearch">
<i class="search icon"></i>
Buscar
</button>
</div>

JS

$("#idDrop").dropdown({
fullTextSearch: 'exact',
on: $('#btnSearch').click(),
apiSettings: {
cache: false,
saveRemoteData: false,
url: ROOT_URL + '/url/url?query={query}',
onResponse: function (response) {
— do some stuffs
return response;
}
},
minCharacters: 4,
interruptRequests: false,
filterRemoteData: false,
localSearch: false,
onChange: function (value, text, $choice) {
— do some stuffs
}
});

Is there anything I can do in this case or in any other way?

I need to do the research and request only when the button is clicked

How to get co-ordinates of a web element for Chrome or safari using JavaScript

There is an element/button on the bottom left of the page and I want to validate that it’s being appeared at the correct position always, hence I tried to take the X,Y cordinates to validate and have tried using both getLlocation() and getBoundingClientRect() functions.

Here’s how I have tried them :

const element = //providing the xpath of the element
let coordinates=element.getBoundingClientRect();
console.log("Co ordinates :"+JSON.stringfy(coordinates));

I get the error like element.getBoundingClientRect() is not a function, this is the function that is widely used to get the deatils of an element, but I’m not getting where I am doing wrong

Other way I tried is :

const element = //providing the xpath of the element
let coordinates=element.getElementSizeAndLocation();
console.log("Co ordinates :"+JSON.stringfy(coordinates));

This is giving few details not the co ordinates I want, I want the boundary X,Y values of the element

Rock Paper Scissors Game FreeCodeCamp

I am trying to solve a rock paper scissors game on freeCodeCamp. Here is the question:

In the game, there will be multiple rounds. The first to reach three points wins the game.

In this step, you will focus on determining if the player has won the round.

Complete the hasPlayerWonTheRound function. This function has two parameters: player and computer. The function should return true if the player has won the round, and false if the player has lost or tied the round.

Here are the criteria for the player to win a round:

If the player chooses “Rock” and the computer chooses “Scissors”
If the player chooses “Scissors” and the computer chooses “Paper”
If the player chooses “Paper” and the computer chooses “Rock”
A few function calls have been provided for you to test your function.

Here is what I have tried

function hasPlayerWonTheRound(player, computer) {
 if (player === "Rock" && computer === "Scissors") {
  return true;
  }

else if (player =="Scissors" && computer =="Paper") { 
  return true;
  }

else if (player =="Paper" && computer =="Rock") { 
 return true; 
 }

else if (player=="Rock" && computer=="Rock") {
  return false;
}

else if (player=="Paper" && computer=="Paper") {
  return false;
}
else (player=="Scissors" && computer=="Scissors") {
  return false;
}

When I submit this answer it says “Your hasPlayerWonTheRound function should return a boolean.”