Navigation.share modify default prompt on Chrome or others browsers - javascript

I'm trying to use the navigation.share API, in Firefox if i try to share a tweet for example, this open de twitter page and all is ok. But if i try the same in chrome the behavior is different, the share open a default prompt. There are a way to have the same behavior in each browser?
const shareUrl = (e, socialNetwork) => {
e.preventDefault();
e.stopPropagation();
if (navigator.share) {
navigator
.share({
title: document.title,
url: path,
})
.catch(console.error);
} else {
if (socialNetwork == "Facebook") {
shareFacebook(path);
}
if (socialNetwork == "Twitter") {
shareTwitter(path);
}
}
};

Related

Cannot read properties of null on extension

I'm working on on tool that gives desktop notifications when page content has specific change. When I launch extension I have error in console that says " Cannot read properties of null (reading 'innerHTML') at snowAlerts (contentScript.js:26:69)".
When I paste same code in chrome snippets code works fine. Also what is worth to mention is that when I paste document.getElementById("3e731e79875e4d5089360d830cbb3517").innerHTML
in console I receive same error, but when I click on the selector and copy this "3e731e79875e4d5089360d830cbb3517" from elements and replace it in document.getElementById("3e731e79875e4d5089360d830cbb3517").innerHTML I receive correct output. I have no idea what may cause this problem, here is code for notification:
function snowAlerts() {
if (document.getElementById("3e731e79875e4d5089360d830cbb3517").innerHTML != '0') {
console.log("Do something");
function showNotification() {
if (Notification.permission !== 'granted') {
Notification.requestPermission();
} else {
const options = {
body: 'New Alert on SNOW',
dir: 'ltr',
};
const notification = new Notification('SNOW INCIDENT', options);
notification.onclick = function () {
window.open('MY SITE');
};
}
}
showNotification();
}
else {
console.log("Do nothing")
}
}
setInterval(snowAlerts, 5000);

Send message from background.js to popup

I want to implement FCM in my chrome extension.
At the mement after a lot of research I've found that the quick and best way to implement fcm is using the old API chrome.gcm. At the moment this solution seems working fine and when the extension is loaded I'm able to get an fcm token.
Now what I want to do is to pass the token to the popup that is powered by vue.js I'm trying with this code but without success.
background.js
const openPopup = () => {
chrome.windows.create({
type: 'popup',
height: 520,
width: 440,
url: chrome.runtime.getURL('popup.html')
})
}
const registeredToken = (registrationId) => {
console.log('FCM Token')
console.log(registrationId)
openPopup()
chrome.runtime.sendMessage({fcmToken: registrationId})
if( chrome.runtime.lastError ) {
console.log('error')
}
}
const notificationId = (id) => {
if(chrome.runtime.lastError) {
console.log(chrome.runtime.lastError)
}
console.log(id)
}
chrome.runtime.onInstalled.addListener( () => {
console.log('FCM extension installed')
})
chrome.action.onClicked.addListener( (tab) => {
console.log(tab)
openPopup()
})
chrome.gcm.register(['my_sender_id'], registeredToken)
chrome.gcm.onMessage.addListener( (message) => {
console.log(message, message.data["gcm.notification.title"])
chrome.notifications.create('', {
type: 'basic',
iconUrl: 'letter.png',
title: message.data["gcm.notification.title"],
message: message.data["gcm.notification.body"],
buttons: [
{ title: 'Dismiss' },
{ title: 'Reply' }
]
}, notificationId)
})
chrome.notifications.onButtonClicked.addListener( (notificationId, buttonIndex) => {
console.log('button clicked')
console.log(notificationId, buttonIndex)
})
popup.vue file
<template>
<div class="main_app">
<h1>Hello {{msg}}</h1>
</div>
</template>
<script>
export default {
name: 'popupView',
data () {
return {
msg: ''
}
},
mounted() {
chrome.runtime.onMessage( (message, sender, sendResponse) => {
console.log(message, sender, sendResponse)
this.msg = message
})
},
methods: {
}
}
</script>
What I've noticed is that the chrome.runtime.sendMessage({fcmToken: registrationId}) will not work and on the popup side I'm unable to send or get messages from background
How I can pass messages between the vue.js powered popup and the background.js file of the extension?
Is better to use firebase client library to get push messages or the gcm is fine for this scope?
You can use the chrome.tabs.query and chrome.tabs.sendMessage APIs to send a message from the background to the Popup.
chrome.tabs.query({}, function (tabs) {
tabs.forEach((tab) => {
chrome.tabs.sendMessage(
tab.id,
youtPayload,
function (response) {
// do something here if you want
}
);
});
});
That's it!
I spend lots of hours to finding solution to the same proble and still not find any.
My current understanding is, that we are trying to do and use method for the purpose, they wasnt ment to be used for.
Key information leading to this:
popup.js can share the same. Js file and objects with background.js
documentation primarely is talking about passing data between web page (content.js) and others (popup.js or background.js)

detect shake event on iphone

I'm trying to detect a shake event on iPhone. shake.js library is not working, would appreciate any help or other solutions. I've also tried this but no luck.
function ClickRequestDeviceMotionEvent () {
window.DeviceMotionEvent.requestPermission()
.then(response => {
if (response === 'granted') {
window.addEventListener('devicemotion',
() => {
//alert('DeviceMotion permissions granted.');
var o = 0.6; // 0
var myShakeEvent = new Shake ({
threshold: 10, // 15. optional shake strength threshold
timeout: 1000 // optional, determines the frequency of event generation
});
myShakeEvent.start(); // mobile, no ipad
window.addEventListener('shake', shakeEventDidOccur, false);
function shakeEventDidOccur() { // function to call when shake occurs
alert('shake!');
}
},
(e) => { throw e }
)} else {
alert('DeviceMotion permissions not granted.')
}
})
.catch(e => {
alert(e)
})
}
By the looks of it, this isn't possible anymore.
Shake.js was discontinued so is not supported.
Also, Safari does not support the Accelerometer, Gyroscope or the DeviceMotionEvent web API's, so this data is just not available for your code to react to.

Detect when browser back button is pressed - ReactJS

How can I detect when back button on browser (Chrome, FireFox, Safari etc.) is clicked through JavaScript on my React website and take actions accordingly?
Also, when back button on mobile is pressed, is the event same or similar to when back button in browser is clicked?
Looking forward for an answer. Thanks in advance.
Here is a pretty simple custom hook for that:
const useBackButton = () => {
const [isBack, setIsBack] = useState(false);
const handleEvent = () => {
setIsBack(true);
};
useEffect(() => {
window.addEventListener("popstate", handleEvent);
return () => window.removeEventListener("popstate", handleEvent);
});
return isBack;
};
Working example: https://codesandbox.io/s/cranky-borg-5qwl3?file=/src/index.js
Objective approach:
constructor() {
super();
this.state = {
isBack: false
};
this.onPopstate = this.onPopstate.bind(this)
}
onPopstate() {
this.setState({ isBack: true });
alert("back!!!");
}
componentDidMount() {
window.addEventListener("popstate", this.onPopstate);
}
componentWillUnmount() {
window.removeEventListener("popstate", this.onPopstate, false);
}
Add these 2 lines into your componentDidMount().This worked for me
window.history.pushState(null, null, document.URL);
window.addEventListener('popstate', function(event) {
window.location.replace(`YOUR URL`);
});
This works some of the time, but there's no reliable way to detect stuff like this, as of now.
window.addEventListener("beforeunload",function(){
//Checking if the user hasn't clicked on something on the page
if(document.activeElement==document.querySelector("body")){console.log("Back Button Maybe?")}
})

How can I mimic onbeforeunload in a Vue.js 2 application?

I have a Vue component that is tracking when it is "dirty" (e.g. unsaved). I would like to warn the user before they browse away from the current form if they have unsaved data. In a typical web application you could use onbeforeunload. I've attempted to use it in mounted like this:
mounted: function(){
window.onbeforeunload = function() {
return self.form_dirty ? "If you leave this page you will lose your unsaved changes." : null;
}
}
However this doesn't work when using Vue Router. It will let you navigate down as many router links as you would like. As soon as you try to close the window or navigate to a real link, it will warn you.
Is there a way to replicate onbeforeunload in a Vue application for normal links as well as router links?
Use the beforeRouteLeave in-component guard along with the beforeunload event.
The leave guard is usually used to prevent the user from accidentally
leaving the route with unsaved edits. The navigation can be canceled
by calling next(false).
In your component definition do the following:
beforeRouteLeave (to, from, next) {
// If the form is dirty and the user did not confirm leave,
// prevent losing unsaved changes by canceling navigation
if (this.confirmStayInDirtyForm()){
next(false)
} else {
// Navigate to next view
next()
}
},
created() {
window.addEventListener('beforeunload', this.beforeWindowUnload)
},
beforeDestroy() {
window.removeEventListener('beforeunload', this.beforeWindowUnload)
},
methods: {
confirmLeave() {
return window.confirm('Do you really want to leave? you have unsaved changes!')
},
confirmStayInDirtyForm() {
return this.form_dirty && !this.confirmLeave()
},
beforeWindowUnload(e) {
if (this.confirmStayInDirtyForm()) {
// Cancel the event
e.preventDefault()
// Chrome requires returnValue to be set
e.returnValue = ''
}
},
},
The simplest solution to mimic this fully is as follow:
{
methods: {
beforeWindowUnload (e) {
if (this.form_dirty) {
e.preventDefault()
e.returnValue = ''
}
}
},
beforeRouteLeave (to, from, next) {
if (this.form_dirty) {
next(false)
window.location = to.path // this is the trick
} else {
next()
}
},
created () {
window.addEventListener('beforeunload', this.beforeWindowUnload)
},
beforeDestroy () {
window.removeEventListener('beforeunload', this.beforeWindowUnload)
}
}

Categories

Resources