How to find out if a user is dragging a tab - google-chrome-extension

I am trying to figure out, if a user is dragging a tab, any tab. I don't care which tab it is, I just need to know, if any tab is being dragged.
What is the best way to do this?
Please note: I asked a similar question. However, in that other question I wanted to know, when dragging stopped so I could perform my move operation. The solution given there (retrying until it works) doesn't seem to apply to this new question.

There is no way to tell whether any tab is being "dragged" (=mouse button held down on a tab).
If you want to know that a tab drag has occurred (opposed to "is about to happen"), then you could use the chrome.tabs.onMoved (moved within a tab) and/or chrome.tabs.onAttached / chrome.tabs.onDetached events.

I built a solution based on the fact that Chrome doesn't allow the moving of tabs in the window that contains a tab that is currently being dragged.
In this case, chrome.runtime.lastError.message will be Tabs cannot be edited right now (user may be dragging a tab).
I utilize this by getting the first tab of the focused window and moving it to its index. Because I use its own index, there isn't actually a visual change, when the operation succeeds.
var Chrome = {
isUserDragging: function (callback) {
chrome.windows.getAll({ populate: true }, function (windows) {
var window = windows.filter(function (x) {
return x.type === 'normal' && x.focused && x.tabs
&& x.tabs.length;
})[0];
if (window === undefined)
return;
var tab = window.tabs[0];
chrome.tabs.move(tab.id, { index: tab.index }, function () {
callback(
chrome.runtime.lastError !== undefined &&
chrome.runtime.lastError.message.indexOf('dragging') !== -1);
});
});
}
}
Usage would be:
Chrome.isUserDragging(function(userIsDragging) {
if(userIsDragging)
// do something
else
// do something else
});
Now, based on this, I built a polling mechanism using setTimeout that checks periodically if the user is still dragging and executes an action, when the user stopped dragging.
The full implementation can be seen here and it uses these two helper classes.

Related

How do I remove a history entry in GreaseMonkey? [duplicate]

Using the HTML5 window.history API, I can control the navigation pretty well on my web app.
The app currently has two states: selectDate (1) and enterDetails (2).
When the app loads, I replaceState and set a popState listener:
history.replaceState({stage:"selectDate",...},...);
window.onpopstate = function(event) {
that.toStage(event.state.stage);
};
When a date is selected and the app moves to stage 2 I push state 2 onto the stack:
history.pushState({stage:"enterDetails",...},...);
This state is replaced anytime details change so they are saved in the history.
There are three ways to leave stage 2:
save (AJAX submit)
cancel
back button
The back button is handled by the popstate listener. The cancel button pushes stage 1 so that the user can go back to the details they were entering the back button. These both work well.
The save button should revert back to stage 1 and not allow the user to navigate back to the details page (since they already submitted). Basical, y it should make the history stack be length = 1.
But there doesn't seem to be a history.delete(), or history.merge(). The best I can do is a history.replaceState(stage1) which leaves the history stack as: ["selectDate","selectDate"].
How do I get rid of one layer?
Edit:
Thought of something else, but it doesn't work either.
history.back(); //moves history to the correct position
location.href = "#foo"; // successfully removes ability to go 'forward',
// but also adds another layer to the history stack
This leaves the history stack as ["selectDate","selectDate#foo"].
So, as an alternative, is there a way to remove the 'forward' history without pushing a new state?
You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).
One option I've been looking into is to handle the history yourself in JavaScript and use the window.history object as a carrier of sorts.
Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.
var myHistory = [];
function pageLoad() {
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data.
}
Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState to keep the browser out of the loop.
function nav_to_details() {
myHistory.push("page_im_on_now");
window.history.replaceState(myHistory, "<name>", "<url>");
//Load page data.
}
When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.
function on_popState() {
// Note that some browsers fire popState on initial load,
// so you should check your state object and handle things accordingly.
// (I did not do that in these examples!)
if (myHistory.length > 0) {
var pg = myHistory.pop();
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data for "pg".
} else {
//No "history" - let them exit or keep them in the app.
}
}
The user will never be able to navigate forward using their browser buttons because they are always on the newest page.
From the browser's perspective, every time they go "back", they've immediately pushed forward again.
From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).
From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).
If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...
var myHistory = [];
function pageLoad() {
// When the user first hits your page...
// Check the state to see what's going on.
if (window.history.state === null) {
// If the state is null, this is a NEW navigation,
// the user has navigated to your page directly (not using back/forward).
// First we establish a "back" page to catch backward navigation.
window.history.replaceState(
{ isBackPage: true },
"<back>",
"<back>"
);
// Then push an "app" page on top of that - this is where the user will sit.
// (As browsers vary, it might be safer to put this in a short setTimeout).
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
// We also need to start our history tracking.
myHistory.push("<whatever>");
return;
}
// If the state is NOT null, then the user is returning to our app via history navigation.
// (Load up the page based on the last entry of myHistory here)
if (window.history.state.isBackPage) {
// If the user came into our app via the back page,
// you can either push them forward one more step or just use pushState as above.
window.history.go(1);
// or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
}
setTimeout(function() {
// Add our popstate event listener - doing it here should remove
// the issue of dealing with the browser firing it on initial page load.
window.addEventListener("popstate", on_popstate);
}, 100);
}
function on_popstate(e) {
if (e.state === null) {
// If there's no state at all, then the user must have navigated to a new hash.
// <Look at what they've done, maybe by reading the hash from the URL>
// <Change/load the new page and push it onto the myHistory stack>
// <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>
// Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
window.history.go(-1);
// Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
// This would also prevent them from using the "forward" button to return to the new hash.
window.history.replaceState(
{ isBackPage: false },
"<new name>",
"<new url>"
);
} else {
if (e.state.isBackPage) {
// If there is state and it's the 'back' page...
if (myHistory.length > 0) {
// Pull/load the page from our custom history...
var pg = myHistory.pop();
// <load/render/whatever>
// And push them to our "app" page again
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
} else {
// No more history - let them exit or keep them in the app.
}
}
// Implied 'else' here - if there is state and it's NOT the 'back' page
// then we can ignore it since we're already on the page we want.
// (This is the case when we push the user back with window.history.go(-1) above)
}
}
There is no way to delete or read the past history.
You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:
popstate event can happen when user goes back ~2-3 states to the past
popstate event can happen when user goes forward
So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.
A simple solution:
var ismobilescreen = $(window).width() < 480;
var backhistory_pushed = false;
$('.editbtn').click( function()
{
// push to browser history, so back button will close the editor
// and not navigate away from site
if (ismobilescreen && !backhistory_pushed)
{
window.history.pushState('forward', null, window.location);
backhistory_pushed = true;
}
}
Then:
if (window.history && window.history.pushState)
{
$(window).on('popstate', function()
{
if (ismobilescreen && backhistory_pushed && $('.editor').is(':visible'))
{
// hide editor window (we initiate a click on the cancel button)
$('.editor:visible .cancelbtn').click();
backhistory_pushed = false;
}
});
}
Results in:
User opens editor DIV, the history state is saved.
User hits back button, history state is taken into account.
Users stays on page!
Instead of navigating back, the editor DIV is closed.
One issue: If you use a "Cancel" button on your DIV and this hides the editor, then the user has to click the mobile's back button two times to go back to the previous URL.
To solve this problem you can call window.history.back(); to remove the history entry by yourself which actually deletes the state as requested.
For example:
$('.btn-cancel').click( function()
{
if (ismobilescreen && backhistory_pushed)
{
window.history.back();
}
}
Alternatively you could push a URL into the history that holds an anchor, e.g. #editor and then push to history or not if the anchor exists in the recent URL or not.

Cypress: How to know if element is visible or not in using If condition?

I want to know if an element is visible or not. I am not sure how to do that.
I know that we can run this:
cy.get('selector').should('be.visible')
But if element is invisible then test is failed. So I just want a boolean value if element is not visible so I can decide through if condition.
Use case:
I want to open a side menu by clicking on the button only if sidebar is invisible.
if(sidebarIsInvisible){
cy.get('#sideMenuToggleButton').click();
}
Is this possible?
I really appreciate for any contribution.
Thanks in advance
Cypress allows jQuery to work with DOM elements so this will work for you:
cy.get("selector_for_your_button").then($button => {
if ($button.is(':visible')){
//you get here only if button is visible
}
})
UPDATE: You need to differentiate between button existing and button being visible. The code below differentiates between 3 various scenarios (exists & visible, exists & not visible, not exists). If you want to pass the test if the button doesn't exist, you can just do assert.isOk('everything','everything is OK')
cy.get("body").then($body => {
if ($body.find("selector_for_your_button").length > 0) {
//evaluates as true if button exists at all
cy.get("selector_for_your_button']").then($header => {
if ($header.is(':visible')){
//you get here only if button EXISTS and is VISIBLE
} else {
//you get here only if button EXISTS but is INVISIBLE
}
});
} else {
//you get here if the button DOESN'T EXIST
assert.isOk('everything','everything is OK');
}
});
You can also use my plugin cypress-if to write conditional command chains
cy.get('...').if('visible').click()
Read https://glebbahmutov.com/blog/cypress-if/
try this code:
isElementVisible(xpathLocater) {
this.xpath(xpathLocater).should('be.visible');
};
isElementNotVisible(xpathLocater) {
this.xpath(xpathLocater).should('not.exist');
};
then use these two methods with if statement like shown below:
if(isElementNotVisible) {
}
or
if(isElementVisible) {
}

Hide Product Catalog standard dashlet for all users in Sugarcrm

How can i hide a standard dashlet named "Product Catalog" from the list which gets displayed in the drawer named "Add a Sugar Dashlet". "Add a Sugar Dashlet" drawer gets displayed when user tries to add a dashlet in any dashbaord in Sugarcrm. Hiding should be done in an upgrade safe way.
Note: I am using Sugarcrm Ver 8.0.0 PRO
One way to accomplish this is by creating a custom override of the DashletselectView where you filter out the Dashlet in question.
The code below does so by overriding an internal function of the view, post-processing its results.
custom/clients/base/views/dashletselect/dashletselect.js
({
extendsFrom: "DashletselectView",
_getDashlets: function() {
var dashlets = this._super("_getDashlets", arguments);
return _.filter(dashlets, function (d) { return d.type !== "product-catalog-dashlet"; });
},
})
Then run Quick Repair & Rebuild so that Sugar detects the presence of the custom file and loads it.

How to run chrome.tabs.insertCSS from the background page on each page?

I'd like to add a custom style sheet in a page without a content script. My CSS is OK, but the code below, using the onUpdated and onCreated event listeners do not work.
Part of manifest.json:
"permissions": [
"http://www.site_domain.com/*",
"tabs"],
background.html:
chrome.tabs.onUpdated.addListener(function (tab) {
var tabUrl = tab.url;
if (tabUrl.indexOf("site_domain") != -1) {
changeBgkColor();
}
});
chrome.tabs.onCreated.addListener(function (tab) {
var tabUrl = tab.url;
if (tabUrl.indexOf("site_domain") != -1) {
changeBgkColor();
}
});
function changeBgkColor(){
chrome.tabs.insertCSS(null, {file:"css/styles.css"})
};
chrome.tabs.onCreate has to be replaced with chrome.tabs.onCreated (with a d!).
After fixing this, you'd better pass a tabId to the chrome.tabs.insertCSS method. Also, reduce the code repetition by merging the event listeners:
chrome.tabs.onCreated.addListener(do_something);
chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
if (info.status == 'complete') do_something(tab);
});
function do_something(tab) {
var tabUrl = tab.url;
if (tabUrl && tabUrl.indexOf("site_domain") != -1) {
// changeBgkColour() here:
chrome.tabs.insertCSS(tab.id, {
file: "css/styles.css"
});
}
}
Since these events are called right after the creation of the tabs. each rule might have to be sufficed with !important, to prevent the rules from being overwritten by style sheets on the page.
According to the documentation of onCreated, the url property may not be set when the event is fired, so add tabUrl && in the condition, to prevent possible errors.
Also, your domain check is insufficient. .indexOf('google.com') would also match http://stackoverflow.com/q/x/what-is-google.com?.
I'm pretty much doing the same with Chrome 23 (late 2012) and to me it seems that
onCreate is not needed anymore (onUpdated will be fired perfectly even with a cold start and a tab not selected)
changeInfo status "loading" injects the script pretty fast, but it may end up injected twice, even worse, way too early (it shows up in the inspector, but most rules will be overwritten by the page's rules; importants are mandatory)
with changeInfo status "complete" the script is inserted much later (sometimes with bigger load times this can be quite annoying), but it's more stable and for some reason it's not shown in the inspector.
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status === "complete") {
chrome.tabs.insertCSS(tabId, {code: "body{border:1px solid red}"});
}
})
(I'm not really sure if it is an answer per se, unfortunately this post is too long to be a comment - for the url checking I myself use regexp of course, but this has already been noted above)

Add event listener to only 1 tab in Chrome extension

In my Chrome extension, I want to listen for changes to one particular tab only. Using the chrome.tabs.onUpdated.addListener method, my observation is that this runs on ALL tabs. I have implemented a way to capture the id of the tab that I'm interested in and then check that first, like so:
var extTabId = 10; // captured when this tab is created
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (tabId !== extTabId) {
return false;
}
// do whatever else I need this specific tab in question to do
});
Is there an easier way do this so that I only add a listener for extTabId?
There is no simpler solution, your approach is the way to go.

Resources