window.addEventListener is not working on a user click on the browser back button in polymer 2.0? - polymer

window.addEventListener('popstate', function(event) {
alert("you are not able to push back button");
});
I have create the web application using polymer 2.0 but I have to click on the back button to the browser is logout I have to show the alert if the user is click on the back button of the browser I have tried window.addEventListener but still got error.

I've not been able to stop the browser's back button, but I've managed to get around it. In my app, I want to warn the user that they will log out by backing up to the first page, and give them a chance to leave or stay put. Using the polymer-2-starter-kit as my starting point, and tracking a connected property, I got this working:
_routePageChanged(page) {
// If no page was found in the route data, page will be an empty string.
// Default to 'home' in that case.
this.page = (page && this.connected) ? page : 'home';
// Close the drawer.
this.drawerOpened = false;
}
_pageChanged(page, oldPage) {
// Warn user if backing up logs out.
if ((page == '' || page == 'home') && this.connected) {
if (window.confirm("Do you really mean to logout?")) {
this.$.xhrLogout.generateRequest();
} else {
window.history.forward();
}
}
const resolvedPageUrl = this.resolveUrl('my-' + page + '.html');
Polymer.importHref(
resolvedPageUrl,
null,
this._showPage404.bind(this),
true);
}
So if the user is connected, and navigates to the initial page, I can force them to stay on the page where they were with window.history.forward().

Related

chrome.tabs.onUpdated.addListener triggers multiple times

I observe that the onUpdated listener for the tabs API in Chrome does trigger multiple times.
When I refresh the existing tab, the alert pops up 3 times
When I load a different URL, the alert pops up 4 times
In the alert popup, I also see that there seem to be "intermediate" title tags.
How can I avoid this and reduce action to the final update?
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
/*
Multiple Tasks:
1. Check whether title tag matches the CPD Teamcenter title and custom success tab does not exist
2. If yes, trigger three actions:
a. move tab to new Chrome window
b. call external application to hide the window with the isolated tab
c. add custom success tag to identify that this was already processed
*/
const COMPARESTRING = "My Tab Title"
var title = tab.title;
alert(title) // this alert pops up 3 or 5 times!
/* if (title == COMPARESTRING) {
return "Match. :-)";
} else {
return "No match. :-(";
} */
});
you can do something like this
chrome.tabs.onUpdated.addListener(function (tabId, tabInfo, tab): void {
if (tab.url !== undefined && tabInfo.status === "complete") {
// do something - your logic
};
});

React Router v4 - How to detect back button navigation vs url refresh?

I have a url at /page (PAGE A) where I want to detect if the page was navigated to with history back from (PAGE B) or if the user was on (PAGE A) and manually refreshed the page from the URL bar refresh button (without using history back).
I looked into all the history, location, props by react router but didn't find a way to differentiate how the user navigated to the page.
In both scenarios, the history.action == 'POP' is the history action. Ideally it would be 'POP' when using the back button in the app to go back from page b to page a, and when on page a, when refreshing the page, it would be something other than 'POP' like 'REFRESH' for example.
How can we differentiate between both of them to run different logic in our app, since both trigger 'POP'?
Instead of comparing the history key, you can compare the pathname, for example, if you are in the page "/page1/page2" and hit refresh, the new location is the same. But if you hit the back action, the new location will be "/page1/".
This solution also uses a listener to listen to any action coming from history.
componentDidMount() {
const unlisten = history.listen((location, action) => {
if (action == 'POP') {
\\ thisLocation is the current location of your page
if (location.pathname != '/thisLocation/') {
alert('Back Pressed: ' + String(location.pathname));
} else {
alert('Refreshed: ' + String(location.pathname));
}
}
});
this.setState({ ...this.state, unlisten: unlisten });
}
componentWillUnmount() {
this.state.unlisten();
}
You can see more details in the link provided by Rei Dien as a comment of your question: https://www.npmjs.com/package/history
[EDIT]
Another way to do this is using https://www.npmjs.com/package/react-router-last-location and doing this:
import { useLastLocation } from 'react-router-last-location';
componentDidMount() {
const unlisten = history.listen((location, action) => {
const lastLocation = useLastLocation();
if (location.pathname == lastLocation.pathname) {
alert('Back Pressed: ' + String(location.pathname));
}
}
});
this.setState({ ...this.state, unlisten: unlisten });
}
componentWillUnmount() {
this.state.unlisten();
}
The downside is that there is no difference between activating the back action or clicking in a link that goes to the page that you was before, both would be detected as pressing back. If you don't want a new dependency, you can do it manually as stated in https://github.com/ReactTraining/react-router/issues/1066#issuecomment-412907443 creating a middleware.
I think this will at least point your in the right direction. Navigate to yourwebsite.com.
let current_page = history.state.key
if(history.action == 'POP') {
if(history.state.key == current_page) {
return 'page was refreshed'
}
return 'back button was pressed'
}

How to disable the context menu on long press when using device mode in Chrome?

How to disable the context menu on long press when using device mode in Chrome ?
I mean this context menu:
I am asking this because I want to debug long press gestures for mobile devices and the context menu causes my react app to behave in a strange way:
when I try to reorder the list then "strange things start to happen": selected item starts to float all over the place (as can be seen from snapshot below). The Hello World is obscured by the selected item. Really strange.
My workaround is entering this code into the JS console when testing long press actions in device mode:
window.oncontextmenu = function() { return false; }
I have developed a slightly more "advanced" workaround that will still (most of the time) show the contextmenu on right-click while preventing it from showing on a simulated long-tap:
window.oncontextmenu = function() {
if (event.button != 2 && !(event.clientX == event.clientY == 1)) {
event.preventDefault();
}
}
#marsk comment was right therefore based on previous answers I come up with another solution using PointerEvent.pointerType
window.oncontextmenu = function (event: any) {
// eslint-disable-next-line no-console
console.log(event); // prints [object PointerEvent]
const pointerEvent = event as PointerEvent;
// eslint-disable-next-line no-console
console.log(`window.oncontextmenu: ${pointerEvent.pointerType}`);
if (pointerEvent.pointerType === 'touch') {
// context menu was triggerd by long press
return false;
}
// just to show that pointerEvent.pointerType has another value 'mouse' aka right click
if (pointerEvent.pointerType === 'mouse') {
// context menu was triggered by right click
return true;
}
// returning true will show a context menu for other cases
return true;
};

[FireFox][HTML5 FullScreen API] How can I detect whether user clicked 'allow' button and allow full-screen mode

I'm researching and using html5 full-screen API with FireFox, I have a local html file, name 'SamplePlayer.html'. If I launched this file and clicked 'Full' button to make one element in to fullscreen mode like:
function launchFullScreen (element) {
if (typeof(element) == "undefined")
element = document.documentElement;
if (element.requestFullScreen) {
element.requestFullScreen();
}
else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
}
else if(element.webkitRequestFullScreen) {
element.webkitRequestFullScreen();
}
return true;
}
FireFox shows a dialog(maybe something else)'Press ESC to exit fullscreen, allow fullscreen, allow, reject', my question is , How can I detect user click 'allow' button and this dialog disappear? not merely element come into full mode and the dialog still exist.
I' ve test with:
document.addEventListener('webkitfullscreenchange', adjustElement, false);
document.addEventListener('mozfullscreenchange', adjustElement, false);
document.addEventListener('fullscreenchange', adjustElement, false);
function adjustElement() {
//alert("change");
//var tmp = fullscreenElement();
var tmp = fullscreen();
alert(tmp);
}
function fullscreenElement() {
return document.fullscreenElement ||
document.webkitCurrentFullScreenElement ||
document.mozFullScreenElement ||
null;
}
function fullscreen() {
return document.fullscreen ||
document.webkitIsFullScreen ||
document.mozFullScreen ||
false;
}
But while user request fullscreen, whether user clicked 'allow' button or not, all those function return true, how can I detect whether user clicked 'allow' button and allow full-screen mode with FireFox?
You cannot detect if the "Allow" button was clicked, and you're not supposed to detect it or be able to detect it either. It is a user decision and implementation detail.
Should there be some "hack" to detect it, it would be an implementation detail that is subject to change at any time, and there is a good chance it will change simply to close this information leak.
What you are able to detect and supposed to work with is entering/existing full screen mode state changes, via the mozfullscreenchange event. See the Using fullscreen mode documentation.

Chrome Extension doesnt work for first few times

I have just built a chrome extension. It changes the context menu using the following -
In content script
document.addEventListener("mousedown", function(event){
if(event.button == 2) {
if (isNaN(window.getSelection().toString())){
chrome.extension.sendRequest({cmd: "createStringMenu"});
}
else {
chrome.extension.sendRequest({cmd: "createNumberMenu"});
}
}
}, true);
In Background
chrome.extension.onRequest.addListener(function(request) {
if(request.cmd == "createStringMenu") {
chrome.contextMenus.removeAll(function() {
chrome.contextMenus.create({"title": "Send ' %s ' as SMS ", "contexts": ['selection'],"onclick": send_as_sms});
});
} else if(request.cmd == "createNumberMenu") {
chrome.contextMenus.removeAll(function() {
chrome.contextMenus.create({"title": "Send SMS to %s ", "contexts": ["selection"],"onclick": send_sms_to});
});
}
});
Whenever the extension runs for the first time either on a newly opened browser or when the extension is installed ( and web pages are refreshed) , no menu is created. then onwards, it does.
What should I do? What could be causing it?
It happens because the context menu appears before the background page can change the content of that context menu. The second time you right-clicked, background page has already changed the content in the first time you pressed, so it works in the second time.