Cannot Access cssRules for Stylesheet CORS

So I’ve been reading that you can’t access cssRules for external stylesheets because it runs into CORS policy issues.

I decided to take a different approach but I’m still running into issues.

My Approach:

  1. Download the css files on the backend and upload them to S3 Bucket
  2. Return back a existing link and new link for match purposes
  3. Delete existing link tag and add in a new tag that will point to my CDN
  4. Access document.styleSheets
  5. Tadaaaa (but this fails)

What I’m trying to figure out is why am I still running into issues if my CDN allows access from any origin?

export default () => {
  const payload = [...document.styleSheets].filter(s => s.href).map(s => s.href);

  axios.post('SOME ENDPOINT', { css: payload }).then(({ status, data: { data: newLinks } }) => {
    if (status === 200) {
      for (const i in newLinks) {
        document.querySelector(`link[href="${newLinks[i].source}"]`).remove()
        const stylesheet = document.createElement('link');
        stylesheet.rel = 'stylesheet';
        stylesheet.href = newLinks[i].downloaded;
        document.getElementsByTagName('head')[0].appendChild(stylesheet);
      }
    }
  }).then(() => {
    let delay = 250
    setTimeout(() => {
      console.log('Stylesheets with Removed Links', [...document.styleSheets]);
    }, delay)
  }).then(() => {
    console.log([...document.styleSheets])
  })
}

Stylesheets

S3 CORS

I have seen this link Cannot access cssRules from local css file in Chrome 64

Why is my executeScript not working ? Chrome extension development:

I am working on a chrome extension that takes a name and a second name from user, and replaces all instances of name with second name on the tab the user is on. The logic is really easy, however, getting the input from the user and using it on the page is extremely challenging.

This is what I have:

Manifest.json:

{
  "manifest_version": 3,
  "name": "Background Changer",
  "version": "1.0.0",
  "description": "Does stuff with the background.",
  "action": {
    "default_title": "lol",
    "default_popup": "index.html"
  },
  "permissions": ["scripting", "tabs", "activeTab"],
  "host_permissions": ["<all_urls>"]
}

index.html

 <h2>Dead Name</h2>
  <input type="text" id="deadName">

  <h2>Real name</h2>
  <input type="text" id="realName">

  <input type="submit" id="submitButton">
    <script src="popup.js"></script>

popup.js

let realName = document.getElementById("realName")
let deadName = document.getElementById("deadName")

document.getElementById("submitButton").addEventListener('submit', injectJS);

const tabId = getTabId();
function injectJS(){
    chrome.scripting.executeScript(
        {
          target: {tabId: tabId, allFrames: true},
          files: ['content.js'],
        },
        () => {});
}

content.js

alert("LOL")

Simply put, this code is meant to be a test of injecting Javascript from the extension pop-out to the tab the user is on. Despite me attaching the event listener, and clicking on it, the alert does not appear.

jQuery closest not working on dynamically added table row

I’m adding table rows dynamically with a button “Add New Line”. When clicked, this fires off a jQuery event which creates a new table row containing form fields. The form fields allow numeric values only.

When a value gets entered into the field, it calculates VAT and Line Total amounts. These totals then get appended to the closest() table row <tr>.

The code works fine for the first row. As soon as a new row is added, the code stops working and values are calculated for the second row.

I believe this has something to do with the fact the rows (and form fields) are dynamically created by jQuery and injected into the page, so closest() cant’t find them.

Whats the solution to this?

Thanks in advance.

Javascript:

$(document).ready(function () {
    var counter = 2;

    $("#addRow").on("click", function () 
    {
        var newRow = $("<tr>");
        var cols = "";

        cols += '<td>' + counter + '</td>';
        cols += '<td><textarea class="form-control" name="description[' + counter + ']"></textarea></td>';
        cols += '<td><input type="text" class="form-control line-quantity" name="quantity[' + counter + ']" onkeypress="return isNumberKey(event)"></td>';
        cols += '<td><input type="text" class="form-control line-price" name="unit_price[' + counter + ']" onkeypress="return isNumberKey(event)"></td>';
        cols += '<td class="line_vat">£0.00</td>';
        cols += '<td class="line_total">£0.00</td>';
        cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger"  value="Delete"></td>';
        newRow.append(cols);
        $("table.table-striped").append(newRow);
        counter++;
    });

    $("table.table-striped").on("click", ".ibtnDel", function (event) 
    {
        $(this).closest("tr").remove();
        counter -= 1
    });

    // Update line vat & subtotal
    $(".line-quantity, .line-price").on("blur", function (event)
    {
        var line_qty = 0;
        var line_price = 0;
        var line_subtotal = '0.00';
        var vat = '0.00';
        var line_total = '0.00';

        line_qty = $(this).closest('#quote_table').find('input.line-quantity').val();
        line_price = $(this).closest('#quote_table').find('input.line-price').val();

        // calculate total line price
        line_subtotal = line_price*line_qty;

        // Calculate VAT
        vat = line_subtotal*1.2-line_subtotal;

        // Line total
        line_total = line_subtotal+vat;
        
        // Update view with totals
        $(this).closest('tr').find('td.line_vat').html(vat.toLocaleString('en-US', {style: 'currency',currency: 'GBP'}));
        $(this).closest('tr').find('td.line_total').html(line_total.toLocaleString('en-US', {style: 'currency',currency: 'GBP'}));

        // Calculate totals at end of table

    });
});

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
    return false;
    return true;
}

HTML:

<form method="post" action="{{ url('cp/quotes/create') }}">
    {{ csrf_field() }}
    <div class="form-group">
      @if($contacts->isEmpty())
      <a href="/cp/contacts/create">Create first contact</a>
      @else
      <label for="contact">Contact</label>
      <!-- Get the selected contact and fetch properties -->
      <select class="form-control selectpicker show-tick" data-live-search="true" id="contact" name="contact" data-live-search-placeholder="Find contact...">
        <option value="">Select a contact...</option>
      @foreach($contacts as $contact)
        <option data-tokens="{{ $contact->id }}" value="{{ $contact->id }}">{{ $contact->contact_name }} ({{ $contact->first_name }} {{ $contact->last_name }})</option>
      @endforeach
      </select>
      <!-- List contact properties -->
      <div class="btn-group-vertical property_list" role="group" aria-label="Property" id="property_list"></div>
      @endif
    </div>
    <div class="form-group">
      <label class="control-label" for="raised_date">
       Date
      </label>
      <div class="input-group">
        <div class="input-group-addon">
          <i class="fa fa-calendar"></i>  
        </div>
        <input class="form-control" id="raised_date" name="raised_date" type="text"/>
      </div>
    </div>
    <div class="form-group">
      <label class="control-label" for="raised_date">
       Expiry Date
      </label>
      <div class="input-group">
        <div class="input-group-addon">
          <i class="fa fa-calendar"></i>  
        </div>
        <input class="form-control" id="expiry_date" name="expiry_date" type="text"/>
      </div>
    </div>
    <table class="table table-striped" id="quote_table">
      <thead>
        <tr>
          <th scope="col">Item #</th>
          <th scope="col">Description</th>
          <th scope="col">Quantity</th>
          <th scope="col">Unit Price</th>
          <th scope="col">VAT</th>
          <th scope="col">Amount</th>
          <th scope="col"></th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>1</td>
          <td><textarea class="form-control" name="description[]"></textarea></td>
          <td><input class="form-control line-quantity" name="quantity[]" type="text" onkeypress="return isNumberKey(event)"></td>
          <td><input class="form-control line-price" name="unit_price[]" type="text" onkeypress="return isNumberKey(event)"></td>
          <td class="line_vat">£0.00</td>
          <td class="line_total">£0.00</td>
          <td></td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="5" class="text-end">Subtotal</td>
          <td colspan="2" class="subtotal">£0.00</td>
        </tr>
        <tr>
          <td colspan="5" class="text-end h3">Total</td>
          <td colspan="2" class="total h3">£0.00</td>
        </tr>
      </tfoot>
    </table>
    <a class="btn btn-warning addRow" href="#" id="addRow">Add Line +</a>
    <div class="form-group">
      <br /><button type="submit" class="btn btn-success">Save Quote</button>
    </div>
  </form>

Application screenshot:

enter image description here

How to Parse student marks .txt data to google sheet using google script

I have multiple .txt file that contains students’ mark for each subject.

  1. students’ mark1
  2. students’ mark2

I want to parse the student mark to google sheet using google script and the output should be like this.

  1. Student’s mark sheet.student sheet image

I have a problem with the range of the column as each student they are taking a different number of subject. Is there any suggestion on the parsing method? Thanks.

sheet.getRange(lastRow +1,5,mark.length,marks[1].length).setValues(mark);

Can I respond to packets sent to a website?

I am writing a python program that sends a packet to the server saying ‘hello’, and I would like to know if I could make my server respond based on it saying ‘hello’. My current code for sending a packet is as follows:

import requests
hL = 0

HeaderList = [{'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'},
{'User-Agent': 'Mozilla/4.0 (Windows 7; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'},
{'User-Agent': 'Mozilla/5.0 (Windows 10; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'},
{'User-Agent': 'Chrome (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Geico) Chrome/39.0.2171.95 Safari/537.36'},
{'User-Agent': 'Mozilla/4.0 (Raspberian; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'},
{'User-Agent': 'Mozilla/5.2 (Windows XP; Intel Windows XP) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'},
{'User-Agent': 'Gecko (Bruh; AMD 3600X bruh os) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'},
{'User-Agent': 'Mozilla/4.0 (Windows 42; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'},
{'User-Agent': 'Mozilla/5.0 (deez; nuts) ooga booga (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'},
{'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'},
{'User-Agent': 'Mozilla/4.0 (Windows 7; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'},
{'User-Agent': 'Mozilla/5.0 (Windows 10; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}]

i = 1
url = 'https://www.whatismyip.com/'
payload = open("request.json")
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
r = requests.post(url, data=payload, headers=headers)
    
site = open('site.html', 'w')
site.writelines(str(r.content))

site.close()
print(r.content)

I can use HTML and javascript.

Thanks for your help in advance.

webpack entry filename config used [ext] placeholders not take effect

I’m sorry for my English is low,hope you understand.
I learning how to use webpack build my project.The following is config for two entry files:

 entry:{
    main: {
      import: "./src/main.js",
      filename:"main/[name].[hash:6][ext]",
      dependOn:"lodash"
    },
    index:{
      import:"./src/index.js",
      filename:"index/[name].[hash:6][ext]",
      dependOn:"lodash"
    },
    lodash: {import: [ "lodash" ],filename:"lodash/[name].[hash:6].js" }
  },

I think it will generator two files after I execute the npm run build script,for example,main.a24fc1.js and index.b42afd.js ,their name should look like that.

But in result they is this:

|- build
  |- index
    |- index.81c047[ext]
  |- main
    |- main.81c047[ext]

In their filename config,used [ext] placeholders but it’s not take effect.I don’t know why it happended,becouse my config the same as in webpack document’s demo.

// This is webpack demo config:
module.exports = {
  //...
  entry: {
    app: './app.js',
    home: { import: './contact.js', filename: 'pages/[name][ext]' },
    about: { import: './about.js', filename: 'pages/[name][ext]' },
  },
};

I are unable solve the problem…Thank to everyone helped me!(Please tell me if there are has any English mistakes in this article.^_^)

Can someone help me use react integrated paycard template in open layer payment gateway

I want to put my custom UI instead of open layer payment gateway UI but I am having issues understanding the code of the gateway. From what I have understand that it is ready made UI Payment Gateway and I am having issues replacing styling of this gateway. My website is using Django + React frameworks.

Payment Gateway I am integrating in my website:
https://github.com/bankopen/layer-sdk-python
React Paycard template I want to use:
https://github.com/jasminmif/react-interactive-paycard

Warm Regards
Keshav

How to prevent the textbox in react to cache/autoComplete previous values for any browser

I am bulding a react application where i am using some textboxes to enter some values ,but the problem i am facing is that the textbox is showing the previous values entered from the browser which i don’t want. I have tried using autoComplete=”off” but it is not working. I am posting the code i am using for the application

<div className="myCSS">
<label>Store</label>
<InputNumber mode="decimal" userGrouping ={false}
value={searchCriterias.storeNumber}
id={store_number}
name={store_number} 
autoComplete="off" // Here i am trying to apply the autoComplete 
onChange={(e) =>{     
 modify(store_number,e.target.value);
}}
/>

React key warning on listing component, coming from the parent component

Warning: Each child in a list should have a unique “key” prop. Check the render method of ForwardRef(ListItem). It was passed a child from RecipientsList.

I have traced it down on the react-components debugger chrome tool. I have put the key props on the component but the warning still comes up.

Parent Component (Recipient List)

 <List>
                            {recipientsResults.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((recipient, index) => (
                                <CustomList
                                    key={Math.random() * 10}
                                    title={recipient.account_holder_name}
                                    subtitle={recipient.summary}
                                    id={recipient.id}
                                    avatar={"true"}
                                    customClass={cx(styles.item)}
                                    avatarClass={cx(styles.avatar)}
                                    actions={[
                                        <span className={cx(styles.action)}>
                                             <Icon name="send" />
                                        </span>,
                                        <span className={cx(styles.action)}>
                                                <Icon name={`${index === selectedIndex ? 'caret-up' : 'caret-down'}`} color="#C4C4C4" onClick={() => {
                                                   if (index === selectedIndex) {
                                                       setSelectedIndex(null)
                                                   } else (
                                                       handleBeneficiaryClick(index)
                                                   )

                                                }} />
                                        </span>
                                    ]}
                                    collapsibleContent={
                                        <CollapsibleContent
                                            recipient={recipient}
                                            isOpen={index === selectedIndex}
                                            index={Math.random() * 10}
                                            onDelete={(id) => handleDelete(id)}
                                            onEdit={(id) => handleEdit(id)}
                                        />
                                    }
                                />
                            ))}
                        </List>
                    }

Child Component (Custom List)

 return (
        <>            
            <ListItem
                    secondaryAction={
                        actions && actions
                    }
                    className={`${customClass}`}
                    key={Math.random() * 10}
                >
                    {avatar &&
                    <ListItemAvatar>
                        <Avatar src={avatar} className={`${avatarClass}`}>
                            {getInitials(title)}
                        </Avatar>
                    </ListItemAvatar>
                    }
                    <ListItemText
                        primary={title}
                        secondary={subtitle ? subtitle : null}
                    />
                </ListItem>
                {collapsibleContent && collapsibleContent}
        </>
        )

How to obtain response data from URL scheme in an application?

I’m working on a vue project. Let’s say I have a application called myApp, and I have an authorisation page which will show QRCode in PC. If I open this page in myApp, it will call window.location.replace(myApp://codes/xxxxx) and then redirect the page to the auth page in myApp. In this page, I can simply authorise the user by clicking the button.

My question is, when I open the scheme myApp://codes/xxxxx, it will call the authorise function of myApp, and then I clicked the authorise button, myApp will return some data. I want obtain auth code parameter in the data, how could I obtain it? If there is any ambiguity illustration, please let me know.

Access Vue instance in Nuxt plugin

i created a nuxt plugin to use the simple-jsonrpc-js package together with the nuxt auth plugin. Now i can access it with this.$jsonApi.call() to perform a request to the server with my token provided by nuxt/auth.

I use it in many components within my nuxt app so i wanted to create an error handler for my plugin by wrapping _jrpc.call() in a try-catch block. Because im using Vuetify i want to show a snackbar component with the content of the error Message. Currently my code looks like this:


async call<T = Response<any>>(method: string, data: object = {}): Promise<T> {
    const token = this.accessTokenFactory()
    try {
        return await this._jrpc.call(method, {
            token: token,
            data
        })
    } catch (e:any) {
        const ComponentClass = Vue.extend(VSnackbar)
        const instance = new ComponentClass()
        instance.$slots.default = [e.message]
        instance.$mount()
        document.querySelector('body')?.appendChild(instance.$el)
    }
}

But when i get an error from my api, i get this error from the catch block

enter image description here

Which comes from the vuetify component code:

const {
  bar,
  bottom,
  footer,
  insetFooter,
  left,
  right,
  top,
} = this.$vuetify.application

My guess is that the Vue instance i am using doesn’t have the this.$vuetify.application becuase its not the same as the Vue instance used by the nuxt application…

That’s why im asking: how do i access the same Vue instance in Nuxt when injecting a plugin? The Nuxt docs arent helping and i haven’t found a similar question.

Thanks in advance for helping

Phaser 3: Change width of sprite relative to height

I’d like to be able to change the height of my sprite to fit into a menu, however when I change the height with sprite.displayHeight = menu.height, it’s width won’t scale along and it will be stretched/squashed.

Is there a way to scale the width relative to the height, to keep the sprite’s original ratio?