uBlock Origin in an iFrame

So I’m trying to make a censorship-bypassing proxy and I’m also trying to add an adblocker to the iFrame. I originally forked this from a previous proxy called Shadow that runs on Corrosion. I’m not the greatest at Javascript (I can read it and basically understand all it, but Boxy AI writes all my code) so I’m wondering if its possible at all. Also, I’m running this on CodeSandbox. Any help would be appreaciated.

I got this from the npm obu-core docs

import { StaticNetFilteringEngine } from "@gorhill/ubo-core";

// Create an instance of UboServer
const snfe = StaticNetFilteringEngine.create();

await snfe.useLists([
  fetch("easylist").then((raw) => ({ name: "easylist", raw })),
  fetch("easyprivacy").then((raw) => ({ name: "easyprivacy", raw })),
]);

// Not blocked
if (
  snfe.matchRequest({
    originURL: "https://www.bloomberg.com/",
    url: "https://www.bloomberg.com/tophat/assets/v2.6.1/that.css",
    type: "stylesheet",
  }) !== 0
) {
  console.log(snfe.toLogData());
}

// Blocked
if (
  snfe.matchRequest({
    originURL: "https://www.bloomberg.com/",
    url: "https://securepubads.g.doubleclick.net/tag/js/gpt.js",
    type: "script",
  }) !== 0
) {
  console.log(snfe.toLogData());
}

// Unblocked
if (
  snfe.matchRequest({
    originURL: "https://www.bloomberg.com/",
    url: "https://sourcepointcmp.bloomberg.com/ccpa.js",
    type: "script",
  }) !== 0
) {
  console.log(snfe.toLogData());
}

Currently its having trouble resolving the package name. Don’t know how adblock engines work at all so it’s kind of a mystery.

LINE messaging api+GAS unable to get postback

I am trying to get the answer of date from users via LINE messaging api+GAS.
The template shows on LINE correctly but doesn’t seem like postback works as I expect.
So as I mentioned in the title, I cannot get postback (or datetimepicker) value correctly.
Is there any advice to correct my code?
Appreciate any help.

var channel_token = "●●●"

var url = "https://api.line.me/v2/bot/message/reply";
var user_id = "●●●"
var push_url = "https://api.line.me/v2/bot/message/push"
var spreadsheet = SpreadsheetApp.openById("●●●");
var sheet = spreadsheet.getSheetByName("●●●");


function getUserName(userId) {
  const url = "https://api.line.me/v2/bot/profile/" + userId;
  const response = UrlFetchApp.fetch(url, {
              "headers" : {
              "Authorization" : "Bearer " + channel_token
              }
  });
  return JSON.parse(response.getContentText()).displayName;
}


//LINEからのイベントがdoPostにとんでくる
function doPost(e) {
  //とんできた情報を扱いやすいように変換している
  var json = e.postData.contents
  var events = JSON.parse(json).events;

  //送られてきたテキストを取得
  var user_massage = events[0].message.text;
  const lastRow = sheet.getLastRow() + 1;
  const uidCol = 1
  const nameCol = 2
  const phoneCol = 3
  const bdyCol = 4
  const bdmCol = 5
  const bddCol = 6

  //ここでスプレッドシートの一番下の行に書き込む
  //sheet.appendRow([user_massage]);

  var event=events[0]

  //もしイベントの種類がトークによるテキストメッセージだったら
  if (event.type == "message") {
    if (event.message.type == "text" && event.message.text == "情報を入力してクーポンをゲットします!") {
      //自動返信メッセージの内容
      var uid = event.source.userId;
      sheet.getRange(lastRow, uidCol).setValue(uid)
      sheet.getRange(lastRow, nameCol).setValue(getUserName(uid))
      //もしIDも電話も誕生日もすでにある場合は"すでに登録が完了しています。"//
      //もしIDはあるけど電話がない場合は↓//
      //もしIDはあるけど誕生日がない場合は一番↓//
      var message = {
        "replyToken": event.replyToken,
        "messages": [{ "type": "text", "text": getUserName(uid) + "さん!登録ありがとうございます!電話番号を入力して下さい。※ハイフンなし" }]
      };
    }
    else if (/^[0-9]+$/.test(event.message.text) == true) {
      //もしIDがすでにあったらもう登録がありますを出す。//
      sheet.getRange(lastRow,phoneCol).setValue("'" + event.message.text)
      var flexMessage = {
        "type": "template",
        "altText": "datetime_picker",
        "template": {
            "type": "buttons",
            "thumbnailImageUrl": "https://placehold.jp/00dd82/ffffff/640x480.jpg?text=日時選択", // 画像のURL
            "imageAspectRatio": "rectangle", // 画像のアスペクト比、「rectangle: 1.51:1」・「square: 1:1」、デフォルト値はrectangle
            "imageSize": "cover", // 画像の表示形式
            "imageBackgroundColor": "#3a687e", // 画像の背景色
            "title": "メニュー",
            "text": "以下より選択してください。",
            "defaultAction": {
                "type": "uri",
                "label": "View detail",
                "uri": "https://line.me/ja/"
            },
            "actions": [
                {
                    "type": "datetimepicker",
                    "label": "日時を選択してください。",
                    "data": "action=settime",
                    "mode": "datetime",
                    "initial": "2021-05-12t00:00",
                    "max": "2022-05-12t23:59",
                    "min": "2017-12-25t00:00"
                }
            ]
        }
    };
      var message = {
        "replyToken": event.replyToken,
        //"messages": [{ "type": "text", "text": "生年月日を入力して下さい。お誕生日月にクーポンをお送りします!" }]
        "messages": [flexMessage]
      };
    }
  }
  else if (event.type == "postback"){
    var message = {
    "replyToken": event.replyToken,
    "messages": [{ "type": "text", "text": "postback成功!" }]
    }
  }
  else {
    var message = {
      "replyToken": event.replyToken,
      "messages": [{ "type": "text", "text": "何かが間違ってます。" }]
    }
  }
    var options = {
      "method": "post",
      "headers": {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + channel_token
      },
      "payload": JSON.stringify(message)
    };

    //自動返信メッセージを送信する
    UrlFetchApp.fetch(url, options);
  }```

What is the correct setting for ‘matches’ array in a chrome extension for site filtering

I am creating an extendsion for chrome that I want to only run on certin sites so I set up the content_scripts key in manifest.json as follows

  "content_scripts": [
    {
      "matches": ["https://*.amazon.*/*", "https://*.ebay.*/*","https://*.bestbuy.*/*/"],
      "js": ["src/ethical_extension.js"],
      "run_at": "document_end"
    }
  ]

However the store submission was rejected with:

Violation reference ID: Yellow Magnesium
Violation: Not providing promised functionality
“giving Invalid value for ‘content_scripts[0].matches[0]'”

But setting the matches key to "<all_urls>" the submission is ok and is published just fine!

So my question is the either a required key that needs to be in the matches array for the automated test to pass? Otherwise does the specific site filtering need to be in the content script file directly?

Changing text color on hover with multiline text

Ive just started coding this website for my work and trying to get the text to change color when i hover over it. I have a break in my line of code and its meaning that the text dosent highlight all at once? any suggestions on how i could do this better would be great

CSS:


.column {
    flex: 20%;
    height: 130px;
    padding: 10px;
    margin: 5px;
    text-align: center;
    text-decoration: none;
     
  }
.container {
    display: flex;
    color: #FFFFFF;
    font-family: Arial, Helvetica, sans-serif;
    text-transform: uppercase;
    font-size: 20px;
    text-decoration: none;
  }
.container a {
    text-decoration: none;
    color: #FFFFFF;

}
a:hover {
    color: #977847;

HTML:

<div class='header'>

    <div class="container">
       <span class="column">
          <a href=""> Address line one </a>
        <br>
        <a href=""> Address line two </a>
        <br>
        <br>
        <a> Follow Us: </a> <a href="https://www.facebook.com/"><i class="fa-brands fa-facebook-f" ></i></a>
     </span>
       <div class="column">
         <a> second column </a>
         <a> This is second column of our grid system</a>
       </div>
       <div class="column">
         <a> Third column </a>
         <a> This is third column of our grid system</a>
       </div>
    </div>
</div>

JS:

function updatemenu() {
  if (document.getElementById('responsive-menu').checked == true) {
    document.getElementById('menu').style.borderBottomRightRadius = '0';
    document.getElementById('menu').style.borderBottomLeftRadius = '5';
  }else{
    document.getElementById('menu').style.borderRadius = '0px';
  }
}

Ive tried creating differnt classes based on the element but becuase its in a flexbox the text dosent highlight when you just over over it but when you hover over the whole section. ive tried removing the breaks in the code with pre and white-space formatting but it tends to mess up the whole header formatting. any help apreciated thanks. Ive tried alot of the other posts solutions here and just feel like that my code must be messed up somewhere.

Formatting SQL statement in snowflake using javascript / json

I’m trying to format an SQL statement in Snowflake and I am having some trouble.
Here’s the original statement:

‘snowflake.createStatement(sqlText: “ALTER SESSION SET X = ”{JobN : “+ jobname + “, JobRun: ” + jrid +”, schedule: “+sn+”} ‘ ‘”}).execute();’

Right now the data is output as {JobN: x , JobRun : y , schedule : 123}

i’d like for the output to be {“JobN”: “x” , “JobRun” : “y” , “schedule” : “123”}

I’ve tried using escape characters, and stringify, it doesn’t work. Pretty new to this, would appreciate the help. Thank you!

If statement instead of ternary operator

I try to rewrite the ternary operator into if statement. For some reason it is not working. What am I missing?

function spinalCase(str) {
  let aaa = str.toLowerCase();
  let bbb = ""
  for (let i = 0; i < aaa.length; i++) {
    //bbb += aaa[i] === " " ? "-" : aaa[i]
    if (aaa[i] === " ") {
      aaa[i] === "-"
    }
    bbb += aaa[i]
  }
  console.log(bbb);
}

spinalCase('This Is Spinal Tap');

Return a value from nested function JavaScript

I am relatively new to programming. Would really appreciate some help.

Below is the code:

let containerValue = () => {

   node.childNodes.forEach((container) => {
    container.addEventListener('input', () => {
      let sampleValue;
      if (container.checked == true) {
        sampleValue = container.value;
      }
      console.log(sampleValue); // the result shows up here.
      
    });
  })
}
console.log(containerValue());// Nothing here

I am trying to get the value of sampleValue. I am not sure how to return the values with nested functions.

How to clear the brush (d3) after selection (after the `end` listener callback function)?

I’m using d3 brush as a zoom – to allow me to choose the time range to display from the bigger time range chart.

Therefore this selection:
enter image description here

Should result in the similar chart but for the time range 2004-2012. And that works fine. The issue is that the brush is not cleared and its values don’t make any sense anymore:
enter image description here

But I don’t know how to clear the brush in my code. Here it is:

useEffect(() => {
    const brush = brushX().extent([[0, 0], [innerWidth, innerHeight]]);
    brush(select(brushRef.current));
    brush.on('end', (e) => {
        decodeSelection(e.selection);
    });
    const decodeSelection = (brushExtent) => {
        if (brushExtent) {
            let selectedTimeValues = brushExtent.map(xScale.invert);
            let years = selectedTimeValues.map(date => date.getFullYear());
            onBrush(years);
        } else {
            onBrush(defaultTimeRange);
        }
    }
}, [innerWidth, innerHeight])

I am aware of brush.clear() function and brush.move(null) option but I don’t have an access to brush from my decodeSelection selection function. I have tried passing it but it didn’t work (to be honest I wasn’t surprised, it felt weird to pass brush from brush listener) causing runtine groups is undefined error.

How is it supposed to be done?

Convert an array of objects into a deep tree array using Javascript

I have a complex json file that I have to handle with javascript to make it hierarchical. I am trying to convert an array of objects into a deep nested array. There can be any number of divNames with any number of categories and subcategories

Array of objects:

[{
   divName: "ABC",
   divId: 123,
   catName: "XYZ",
   catId: 456,
   subCatName: "PQR"
   subCatId: 781
},
{
   divName: "ABC",
   divId: 123,
   catName: "YQP",
   catId: 281,
   subCatName: "FYI"
   subCatId: 231
},
{
   divName: "ABC",
   divId: 123,
   catName: "XYZ",
   catId: 456,
   subCatName: "YAB"
   subCatId: 587
}
]

Expected output:

[{divName: "ABC",
  divId: 123
  categories: [
     {
       catName: "XYZ".
       catId: 456,
       subCategories: [
         {
            subCatName: "PQR",
            subCatID: 781
         },
         {
            subCatName: "YAB",
            subCatID: 587
         }],
     {
       catName: "YQP"
       catId: 281,
       subCategories: [
         {
           subCatName: "FYI"
           subCatID: 231
         }
       ]
     }]
  ]

How to use RegEx to set a maximum character limit

currently I am writing a program with a section in it that asks the user for their initials. My problem is that I am unable to set a limit for the number of character that can be inputted to no more than 2. Below is what I have written now:

 var initials = /^[A-Z][A-Z0-9]$/;

I’ve attempted to set the character limit by adding either {2} or {1,2} to make the expression var patt = /^[A-Z][A-Z0-9]{2}$/;, but this has not given my intended result. To be clear, I want the user to add an input such as AD but writing more than 2 letters, such as AMD, would be caught and not accepted. Thanks for the help!

“Cannot read properties of undefined (reading ‘username’)” but works with other properties

The following code:

`<% if (posts) { %>
     <% for (let post of posts.reverse()) { %>
         <div class="card">
             <div class="header">
                 <p><%= post.user.gender %> age: <%= post.user.age %></p>
             </div>
             <div class="card-body">
                 <%= post.body %>
             </div>
             <div class="footer">
                 <%= post.createdAt %>
             </div>
             <div>
                 <% if (post.user.username === currentUser.username) { %>
                     <a href="/post/<%= post._id %>/edit">Edit</a>
                     <a href="/post/<%= post._id %>/delete">Delete</a>
                 <% } %>
             </div>
         </div>
     <% } %>
 <% } else { %>
     <p>There are no posts here yet! Be the first one!!!</p>
 <% } %>`

throws the following error:

C:Usersuserdesktopsecretnodeviewshome.ejs:19 17| 18| >> 19| <% if (post.user.username === currentUser.username) { %> 20| /edit”>Edit 21| /delete”>Delete 22| <% } %> Cannot read properties of undefined (reading ‘username’)

TypeError: C:Usersuserdesktopsecretnodeviewshome.ejs:19 17| 18| >> 19| <% if (post.user.username === currentUser.username) { %> 20| /edit”>Edit 21| /delete”>Delete 22| <% } %> Cannot read properties of undefined (reading ‘username’) at eval (“C:Usersuserdesktopsecretnodeviewshome.ejs”:30:47) at home (C:Usersuserdesktopsecretnodenode_modulesejslibejs.js:703:17) at tryHandleCache (C:Usersuserdesktopsecretnodenode_modulesejslibejs.js:274:36) at exports.renderFile [as engine] (C:Usersuserdesktopsecretnodenode_modulesejslibejs.js:491:10) at View.render (C:Usersuserdesktopsecretnodenode_modulesexpresslibview.js:135:8) at tryRender (C:Usersuserdesktopsecretnodenode_modulesexpresslibapplication.js:657:10) at Function.render (C:Usersuserdesktopsecretnodenode_modulesexpresslibapplication.js


:609:3) at ServerResponse.render (C:Usersuserdesktopsecretnodenode_modulesexpresslibresponse.js:1039:7) at C:Usersuserdesktopsecretnodeapp.js:148:9 at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

It should mean that post.user is undefined. Am I correct?
If that’s true why it doesn’t throw the same error for post.user.gender and post.user.age?
Apparently the same instance of post.user is not undefined and undefined at the same moment???

I logged every post and everyone of them has a user attribute which has a username attribute. I tried to ask chatGPT with no success. I don’t know what else to do.

Python, webscrape. Finding the complete URL, or final html behind javascript w/o selenium

I’m learning Python using AI chat.
As a first challenge, I am making a program that fetches the price of books.
But one of the bookstores are tricky and I’ve been trying different things for days.

They use “reverse” url where the ISBN is at the end, example:
https://www.akademibokhandeln.se/bok/en-varld-utan-slut/9789100172664
and i need to know the middle part of the url.

I have tried

  1. https://www.akademibokhandeln.se/?q=9789100172664
    Then I end up on the start page.

  2. Let python use the search input field, then it shows the book on a temporary search page hidden behind javascript so I can’t webscrape. In firefox inspect mode I see all I need, but not when in the page source mode. https://www.akademibokhandeln.se/sok?sokfraga=9789100172664

  3. The AI-Chat let me test a code to look on the server for easy-to-see urls with the right numbers, but this rarely worked. And I can’t make it present same solution again.

Robots.txt User agent: * Allow: / Sitemap:
https://www.akademibokhandeln.se/sitemap.xml

I’m trying to search all the sitemap files (~20 x 2,5mb) but its often very slow process (72seconds).

import requests
from bs4 import BeautifulSoup

# URL of the sitemap index
sitemap_index_url = "https://www.akademibokhandeln.se/sitemap.xml"

response = requests.get(sitemap_index_url)
soup_index = BeautifulSoup(response.content, "lxml-xml")

# Flag to indicate whether the URL has been found
found = False

# Look for the sitemap URLs in the sitemap index
for sitemap in soup_index.find_all("loc"):
    if found:
        break

    sitemap_url = sitemap.text
    response = requests.get(sitemap_url)
    soup = BeautifulSoup(response.content, "lxml-xml")

    # Look for the URL that ends with "/9789113130378" in each sitemap
    for url in soup.find_all("loc"):
        if url.text.endswith("/9789100172664"):
            print(f"The complete URL is: {url.text}")
            found = True
            break
  1. I tried to webscrape duckduckgo and use the url then my other code.
    I tried to rewrite the duckduckgo url so it becomes a redirect without webscraping.
    https://lite.duckduckgo.com/lite/?kp=-1&kl=se-sv&q=\site:www.akademibokhandeln.se+9789100172664

And now the process are down to 1,5seconds + secondary code.
BUT, duckduckgo are not up to date so new books will make my code to fail.
Google is more up to date but not fully.

  1. Ai-chat often suggests selenium and webdriver as a final solution but I do not want to run more programs just to make this work.

  2. The missing middle part of the url is the book title, I have considered to search for the book title on other place and create the complete url by so, but I have not tested this since it would be slow and not safe.

I believe there is another way. So I can go back to a fast and basic solution which runs on 0,5-1 second, I need to get price directly from searchpage or finalpage

The search page hide the content behind javascript or something, else i could saved the price from here.
The startpage and final page are normal html but i’m missing the full url to get there.

Thanks

JS/HTML replaceChild didn’t work, what should I do?

I tried to test the replaceChild method by replacing the h1 of my html with another h1, but nothing happened.

My js code:

let tituloNovo = document.createElement(‘h1’);
let texto = document.createTextNode(‘Cosa nostra’);

tituloNovo.appendChild(texto);

let tituloAntigo = document.querySelector(‘#título-principal’);
let paiTitulo = tituloAntigo.parentNode;

paiTitulo.replaceChild(tituloNovo, tituloAntigo);

Image movement problem when innering zoom

This is an image when it loads up the browser.

load

When I move the mouse, the lower right corner of the image. The image moves to the top left.

Everything is fine, the zoom works well.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Inner Zoom</title>
  <style>
    #zoom-container {
      width: 300px;
      height: 300px;
      overflow: hidden;
      position: relative;
    }
    #zoomed-image {
      width: 100%;
      height: 100%;
      transform-origin: 0 0;
      transition: transform 0.3s ease-out;
    }
  </style>
</head>
<body>
<div id="zoom-container" onmousemove="zoomImage(event)" onmouseleave="resetZoom()">
  <img id="zoomed-image" src="https://i.stack.imgur.com/JT2CR.jpg" alt="Zoomed Image">
</div>
<script>
  const zoomContainer = document.getElementById('zoom-container');
  const zoomedImage = document.getElementById('zoomed-image');
  function zoomImage(event) {
    const { offsetX, offsetY, target } = event;
    const { width, height } = target.getBoundingClientRect();
    const xPercent = (offsetX / width) * 100;
    const yPercent = (offsetY / height) * 100;
    const scale = 2;
    const translateX = -xPercent * (scale - 1);
    const translateY = -yPercent * (scale - 1);
    zoomedImage.style.transform = `scale(${scale}) translate(${translateX}%, ${translateY}%)`;
  }
  function resetZoom() {
    zoomedImage.style.transform = 'scale(1) translate(0%, 0%)';
  }
</script>
</body>
</html>

https://jsfiddle.net/irankhosravi/upvc51rz/2/

zoom