functionName
существует в контексте контент скрипта.onclick="functionName()"
по клику на нее functionName
будет вызывать в контексте веб страницы, где данной функции нет.addEventListener
на нее.async function timer() {
let countdown = 5;
while (countdown--) {
console.log(countdown + 1);
await sleep(1000);
};
console.log("done");
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
let execId = 0;
async function timer() {
let countdown = 5;
const id = ++execId;
while (countdown--) {
if (id !== execId) {
return;
}
console.log(countdown + 1);
await sleep(1000);
};
console.log("done");
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function hasBanWords(text) {
const url = "banwords.json";
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.send();
return new Promise(resolve => {
xhr.addEventListener("load", function() {
if (this.status === 200) {
const words = JSON.parse(this.response);
const hasSomeWords = words.some(word => text.includes(word));
resolve(hasSomeWords);
}
});
});
}
console.log(await hasBanWords("bitch on the beach"));
function appendScript(src, integrity) {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
script.onload = resolve;
script.onerror = event => reject({message: "Failed to load script", src, integrity, event});
script.src = src;
script.async = true;
if (integrity) {
script.integrity = integrity;
script.crossOrigin = "anonymous";
}
document.body.append(script);
});
}
А что в такой ситуации мешает просто создать объект
export const singleton = {name: "foo"}; // Полноценный синглтон для JS
Какие здесь преимущества именно в создании класса?
instanceof
, чтобы удостовериться, что передается именно инстанс того класса, который может быть лишь в одном экземпляре, а не какой-то другой объект. А если это "просто объект" — ты сможешь подсунуть полную "копию" без каких-либо проблем, создав ее с помощью литеральной записи. Как отключить асинхронность в JS?
XMLHttpRequest
, что в приведенном примере кода как раз таки и сделано. filter.update.country()
this
является объект update
, а не filter
.class Filter {
static sex = null;
static player = null;
static country = null;
static updateSex() {
Filter.sex = document.querySelector("#sex").value;
}
static updatePlayer() {
Filter.player = document.querySelector("#player").value;
}
static updateCountry() {
Filter.country = document.querySelector("#country").value;
}
}
Filter.updatePlayer();
console.log(Filter.player);
class Filter {
constructor() {
this.sex = null;
this.player = null;
this.country = null;
}
updateSex() {
this.sex = document.querySelector("#sex").value;
}
updatePlayer() {
this.player = document.querySelector("#player").value;
}
updateCountry() {
this.country = document.querySelector("#country").value;
}
}
const filter = new Filter();
filter.updateCountry();
console.log(filter.country);
class Filter {
fields = {
country: null,
}
update = {
caller: this,
country() {
this.caller.fields.country = "123";
}
}
}
const filter = new Filter();
filter.update.country();
console.log(filter.fields.country);
"unlimitedStorage"
в manifest.json
browser.storage.local
или в IndexedDB
.chrome.storage.local.get(console.log);
Всегда совпадает с элементом, на котором обработчик события был назначен, в отличие от свойства Event.target
, идентифицирующего элемент, на котором событие возникло.
в чем проблема?
{mode: "no-cors"}
.response
ты не получишь при кросс-доменных запросах с данным режимом.response
годится исключительно только для Cache API в Service Worker. // ==UserScript==
// @name Toster Example
// @match https://qna.habr.com/*
// @match https://toster.ru/*
// @grant GM.xmlHttpRequest
// @connect https://example.com
// ==/UserScript==
!async function() {
console.log("userscript start");
const response = await new Promise((resolve, reject) => {
GM.xmlHttpRequest({
method: "get",
url: "https://example.com",
responseType: "text",
onload: resolve,
onerror: reject,
});
});
console.log("response:", response);
const {response: text} = response;
console.log("text:", text);
}();
@match
), и успешно логирует в консоль содержание https://example.com несмотря на CORS. const blob = new Blob(["The content of the txt file."], {type: "text/plain"});
const blobUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.download = "filename.txt";
a.href = blobUrl;
a.click();
setTimeout(() => URL.revokeObjectURL(blobUrl), 10_000);
в каком виде CryptoJS принимает в себя инстанс объекта самого себя и что он хеширует, чтобы повторить этот метод используя другие инструменты
мне надо чтобы оно НЕ РАБОТАЛО также как и НЕ РАБОТАЕТ в js,
неужели по Вашему я могу переместиться во времени и пространстве к программисту, который когда-то захешировал слово таким методом и сказать ему "эй, ты хешируешь объект, не надо, хешируй строку" и дать ему этот код?
SHA512(
SHA512(
SHA512("hello".getBytes())
)
).toString("hex");
SHA512(
SHA512(
SHA512("hello".getBytes()).toString("hex").getBytes()
).toString("hex").getBytes()
).toString("hex");
чтобы повторить этот метод используя другие инструменты
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.*;
public class Main {
public static void main(String[] args) throws NoSuchAlgorithmException {
byte[] bytesOfMessage = "hello".getBytes(StandardCharsets.UTF_8);
MessageDigest SHA512 = MessageDigest.getInstance("SHA512");
byte[] digest = SHA512.digest(bytesOfMessage);
Main.log(digest);
for (int i = 0; i < 4; i++) {
digest = SHA512.digest(digest);
Main.log(digest);
}
}
private static void log(byte[] digest) {
var hex = new BigInteger(1, digest).toString(16);
if (hex.length() % 2 == 1) {
hex = "0" + hex;
}
System.out.println(hex);
}
}
chrome.storage.local.get(console.log);
chrome.storage.sync.get(console.log);