const menu = {
width: 200,
height: 300,
title: "My menu"
};
console.log(menu);
function multiplyNumeric(obj) {
const data = {}
for (const [key, val] of Object.entries(obj)) {
if (typeof val === 'number') {
data[key]*=2;
}
}
return {
...obj,
...data
}
const updated = multiplyNumeric(menu);
console.log(updated);
// Пример
// Перехват запроса, и блокирование если есть совпадения с url
chrome.webRequest.onBeforeRequest.addListener(
function(details) { return {cancel: true}; },
{urls: ["*://www.domain.com/*"]},
["blocking"]);
const User = require('./models/User')
const facebookStrategy = require('./passports/facebook')
const googleStrategy = require('./passports/google')
module.exports = function (passport) {
passport.serializeUser(function (user, done) {
return done(null, user.id)
})
passport.deserializeUser(async (id, done) => {
try {
const user = await User.findOne({ id })
done(null, user)
} catch (err) {
done(err)
}
})
passport.use(facebookStrategy())
passport.use(googleStrategy())
}
const assert = require('assert')
const FacebookStrategy = require('passport-facebook').Strategy
const User = require('../models/User')
assert(process.env.FACEBOOK_APP_ID)
assert(process.env.FACEBOOK_APP_SECRET)
assert(process.env.APP_URL)
module.exports = () => {
return new FacebookStrategy({
clientID: process.env.FACEBOOK_APP_ID,
clientSecret: process.env.FACEBOOK_APP_SECRET,
callbackURL: `${process.env.APP_URL}/auth/facebook/callback`
},
async (accessToken, refreshToken, profile, done) => {
try {
const user = await User.findOrCreate({ facebook_id: profile.id }, {
facebook_id: profile.id,
name: profile.displayName,
provider: 'facebook'
})
return done(null, user.toJSON())
} catch (err) {
return done(err)
}
})
}
app.get('/auth/facebook', passport.authenticate('facebook'))
app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }, (req, res) => {
const user = req.user;
const payload = {
id: user._id,
email: user.email,
};
jwt.sign(payload, secret, {expiresIn: 3600}, (err, token) => {
if (err) {
res.status(500).send({
error: 'Error signing token',
raw: err,
});
}
// Отдаем html
res.send(`
<script>
localStorage.setItem('token', '${`Bearer ${token}`}');
localtion.href = '/'
</script>
`);
});
})
const passport = require('passport')
require('./passport')(passport)
app.use(passport.initialize())
try {
// код
} catch (Exception $e) {
// Ничего не делаем
}
afterChange
afterChange
оно дальше передается в вверх 1-му слайду (reviews-slider) так как первый слайд подписан на события init reInit afterChange
счетчик изменяетсяafterChange
дальше$('.reviews-gallery-slider').slick(
...
).on('afterChange', function(event, slick){
event.stopPropagation(); // <-
...
});
$examplesSlider2.on('init reInit afterChange', function (event, slick, currentSlide, nextSlide) {
// check
if (!event.target.classList.value.includes('reviews-slider')) {
return;
}
...
});
const App = (...) => {
...
const memorizedMessagesChecked = useMemo(() => <MessagesChechked {...props} />, [props.match.params.id])
return (
<SomeComponents />
{memorizedMessagesChecked}
)
}
class MessagesChechked extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
if (nextProps.match.params.id === this.props.match.params.id) {
return false
}
return true
}
...
}
const MessagesChechked = (...) => {
...
}
const isEqual = (prevProps, nextProps) => {
return prevProps.match.params.id !== nextProps.match.params.id
}
export default React.memo(MessagesChechked, isEqual)
<Route path="/courses" component={Courses}/>
<Link to={`/courses/${course.id}`}>Link to Course</Link>
function fillForm(form) {
var formName = form.id
var json = localStorage.getItem('form['+ formName +']')
var object = JSON.parse(json)
for (var item of Object.entries(object)) {
var key = item[0]
var value = item[1]
var input = form.querySelector('input[name='+ key +']')
input.value = value
}
}
function saveForm(form) {
var formName = form.id
var formData = new FormData(form)
var object = {}
formData.forEach(function(value, key) {
object[key] = value
})
var json = JSON.stringify(object)
localStorage.setItem('form['+ formName +']', json)
}
function syncForm(formName) {
var form = document.getElementById(formName)
fillForm(form)
form.addEventListener('submit', function(event) {
saveForm(event.target)
})
}
syncForm('registration')
telegram_api_key: 'Telegram token',
export TELEGRAM_API_KEY=TelegramToken
TELEGRAM_API_KEY=TelegramToken
require('dotenv').config()
var container = document.getElementById('yohoho')
container.addEventListener('DOMSubtreeModified', function listener(event) {
var iframe = document.getElementById('yohoho-iframe')
if (!iframe) {
// iframe еще не появился в dom
return
}
var url = iframe.src
var updated = url.replace('kLShoChnGWEE', 'LFHkCbyQOWUm')
iframe.src = updated
// Задача выполнена, можно удалить обработчик
container.removeEventListener('DOMSubtreeModified', listener)
})
window.addEventListener('DOMContentLoaded', function(){
var timerId = 0
function changeUrl() {
var iframe = document.getElementById('yohoho-iframe')
if (iframe && iframe.src) {
var url = iframe.src
var updated = url.replace('kLShoChnGWEE', 'LFHkCbyQOWUm')
iframe.src = updated
return clearTimeout(timerId)
}
// Каждые 100 мс делаем проверку на появление iframe в dom
timerId = setTimeout(changeUrl, 100)
}
changeUrl()
})
<input type="text" name="query" value="sort=new&page=1">
<input type="text" name="url" value="">
<button data-key="key1" data-value="value1">Add item 1</button>
<button data-key="key2" data-value="value2">Add item 2</button>
var $inputQuery = $('input[name=query]')
var $inputUrl = $('input[name=url]')
$('button').click(function(event) {
event.preventDefault()
var $this = $(this)
var key = $this.attr('data-key')
var value = $this.attr('data-value')
var query = $inputQuery.val()
var params = new URLSearchParams(query)
params.set(key, value)
var updatedQuery = params.toString()
$inputQuery.val(updatedQuery)
$inputUrl.val('http://test.ru/news?' + updatedQuery)
})
input query: sort=new&page=1&key2=value2&key3=value3
input url: http://test.ru/news?sort=new&page=1&key2=value2&key3=value3
// Сохранить данные
sessionStorage.setItem('username', 'Musk')
// Получить
const username sessionStorage.getItem('username')