i want to get ID of Tab of exist url
For exemple i have 3 tabs in chrome
tab 1 is youtube
tab 2 is google
tab 3 is twitter
and i want get id of tab already existed url google com
Here is an example:
// get all the tabs, you can also limit it to the current window if you wish
// chrome.tabs.query({currentWindow: true}, ...)
chrome.tabs.query({}, tabs => {
// loop through the tabs
for (const tab of tabs) {
if (tab.url === 'theOneYouWant) {
// do whatever needed with tab.id
// break/stop the loop
break;
}
}
});
You can change the code to to check for the domain (not the whole URL) or any other relevant criteria.
Use chrome.tabs API in your extension page such as the browserAction popup or the background script.
manifest.json:
"permissions": ["tabs"]
Simplest case - no variations in domain name:
chrome.tabs.query({url: 'https://www.youtube.com/*'}, tabs => {
// use 'tabs' inside the callback
});
Simple case - variations in sub-domain but the TLD (top level domain) name doesn't have variations:
chrome.tabs.query({url: 'https://*.twitter.com/*'}, tabs => {
// use 'tabs' inside the callback
});
Tough case - TLD varies:
const RE_ALL_GOOGLE = /^https:\/\/(www\.)?google\.([a-z]{2,3}|com?\.[a-z]{2})\//;
// the tabs API doesn't accept wildcards in TLD so we need to enumerate all tabs
// and we restrict the list to https-only as an optimization for the case of many open tabs
chrome.tabs.query({url: 'https://*/*'}, tabs => {
const googleTabs = tabs.filter(({url}) => RE_ALL_GOOGLE.test(url));
// use 'googleTabs' here inside the callback
});
You can write a more restrictive regexp by using the full list of all Google domains and a RegExp generator like this one.
Content scripts can't use chrome.tabs directly so you'll need to do it via a background script.
content script:
chrome.runtime.sendMessage({
action: 'getTabs',
url: 'https://*/*',
// messaging can't transfer regexps so we convert it to a string
pattern: /^https:\/\/(www\.)?google\.([a-z]{2,3}|com?\.[a-z]{2})\//.source,
}, tabs => {
// use 'tabs' inside the callback
});
manifest.json:
"permissions": ["tabs"],
"background": {
"scripts": ["background.js"],
"persistent": false
}
background.js:
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.action === 'getTabs') {
chrome.tabs.query({url: msg.url}, tabs => {
if (msg.pattern) {
const re = new RegExp(msg.pattern);
tabs = tabs.filter(({url}) => re.test(url));
}
sendResponse(tabs);
});
// keep the reponse channel open since the chrome.tabs API is asynchronous
return true;
}
});
Related
I'm trying to add a route parameter to all pages in a Razor Pages Area so every URL within an Area has an OrgId e.g. /dashboard/{orgId}/{page}/{route}. I can add them using the AddAreaPageRoute as shown below, but I can't help feeling there's a way to apply this to all pages without having to define an entry for every page in the Area. Is there a way to create a route for all pages in an Area?
.AddRazorPages(options =>
{
options.Conventions.AddAreaPageRoute("Dashboard", "/Index", "Dashboard/{orgId}");
options.Conventions.AddAreaPageRoute("Dashboard", "/AddItem", "Dashboard/{orgId}/AddItem");
options.Conventions.AddAreaPageRoute("Dashboard", "/Items", "Dashboard/{orgId}/Items");
options.Conventions.AddAreaPageRoute("Dashboard", "/Items/Index", "Dashboard/{orgId}/Items/{id}");
})
You can change your code like below:
services.AddRazorPages(options =>
{
options.Conventions.AddAreaFolderRouteModelConvention("Dashboard", "/", model =>
{
foreach (var selector in model.Selectors)
{
var c = selector.AttributeRouteModel.Template.ToString();
selector.AttributeRouteModel = new AttributeRouteModel
{
Order = -1,
Template =c.Replace("Dashboard", "Dashboard/{orgId}")
};
}
});
});
You can see the details in the doc.
Goal: I would like to achieve github style routing, where abcd in github.com/abcd could resolve to a user profile page or a team page.
I currently have a version that sort of works (see below). Unfortunately I am occasionally getting a white page flash when navigating between 2 dynamic routes.
My server file looks like:
const express = require('express');
const next = require('next');
const { parse } = require('url');
const resolveRoute = require('./resolveRoute');
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const nextApp = next({
dev,
});
const nextHandle = nextApp.getRequestHandler();
const STATIC_ROUTES = [
'/about',
'/news',
'/static',
];
const DYNAMIC_ROUTE_MAP = {
user: '/[user]',
team: '/teams/[team]',
};
nextApp.prepare().then(() => {
const server = express();
server.get('*', async (req, res) => {
// pass through next routes
if (req.url.indexOf('/_next') === 0) {
return nextHandle(req, res);
}
// pass through static routes
if (
req.url === '/' ||
STATIC_ROUTES.map(route => req.url.indexOf(route) === 0).reduce(
(prev, curr) => prev || curr,
)
) {
return nextHandle(req, res);
}
// try to resolve the route
// if successful resolves to an object:
// { type: 'user' | 'team' }
const resolvedRoute = await resolveRoute(req.url);
if (!resolvedRoute || !resolvedRoute.type) {
console.error('🛑 Unable to resolve route...');
return nextHandle(req, res);
}
// set query
const { pathname } = parse(req.url);
const paths = pathname.split('/').filter(path => path.length > 0);
const query = {
[resolvedRoute.type]: paths.length > 0 ? paths[0] : null,
};
// render route
return nextApp.render(
req,
res,
DYNAMIC_ROUTE_MAP[resolvedRoute.type],
query,
);
});
server.listen(port, err => {
if (err) throw err;
console.log(`🌎 Ready on http://localhost:${port}`);
});
});
I'm wondering if there is a better way to handle this or if I need to move away from NextJS.
Next.JS has built in dynamic routing, which shouldn't require you to create a custom server.js file. If you want full compatibility with Next.JS you should use it's dynamic routing instead.
To create a dynamic route in Next.JS you can create pages with names surrounded in square brackets e.g. /pages/[username].js. This will match all routes on your base domain, so you can set up the example you mentioned with github e.g. http://yourwebsite.com/csbarnes and http://yourwebsite.com/anotherusername.
In the example above you can grab the username in your Next.JS page from the query parameter in getInitialProps just in the same way as you would with any query string parameters:
static getInitialProps({query}) {
console.log(query.username); // the param name is the part in [] in your filename
return {query}; // you can now access this as this.props.query in your page
}
Next.JS always matches static routes before dynamic routes meaning your /pages/ directory can look like this:
pages/index.js -> (will match http://yourwebsite.com)
pages/about.js -> (will match http://yourwebsite.com/about)
pages/contact.js -> (will match http://yourwebsite.com/contact)
pages/[username].js -> (will match http://yourwebsite.com/[anything_else])
Multiple segments
You can have multiple segment dynamic routes, such as http://website.com/[username]/[repo] using folders in your pages directory:
pages/[username].js -> (matches http://yourwebsite.com/[username])
pages/[username]/[repo] -> (matches http://yourwebsite.com/[username]/[repo])
In this instance your query object will contain 2 params: { username: ..., repo: ...}.
Route "prefixes"
You can have multiple dynamic routes with different "prefixes" if you wish by creating folders in your pages directory. Here is an example folder structure with a website.com/[username] route and a website.com/teams/[team] route:
Dynamic number of different segments
You can also have dynamic routes with any number of dynamic segments. To do this you need to use an ellipsis ("...") in your dynamic route file name:
/pages/[...userDetails].js -> (will match http://website.com/[username]/[repo]/[etc]/[etc]/[forever])
In this instance your this.props.userDetails variable will return an array rather than a string.
One addition regarding usage of SSR and SSG pages and you need to differentiate those with dynamic URLs by adding the '-ssr' prefix to an URL.
For example, you need some pages to be SSR, then you can create under the pages an ssr folder where you could put the page [[...path]].js with getServerSideProps. Then you could use such rewrite in the next.config.js under async rewrites() {:
{
source: '/:path*/:key-ssr', destination: '/ssr/:path*/:key-ssr'
}
that covers such URLs:
/page-ssr
/en/page1/page-ssr
/en/page1/page2/page-ssr
/en/page1/page2/page3/page-ssr
etc.
You can't have two different types of dynamic routes at one route. The browser has no way of differentiating between a and b, or in your case a username and a team name.
What you can do is have subroutes, lets say /users and /teams, that have their own respective dynamic routes.
The folder structure for that in NextJS would look like this:
/pages/users/[name].js
/pages/teams/[name].js
I have a page with big list of data and some buttons for filtering.
for example 2 buttons to filter by status:
Complete status
Cancel status
I want when the user clicked on the complete the url to be changed to
http://demo.com/list?filter=complete
the page does not reloading, it just for get specific url foreach filter button.
How can I implement the code in Nuxt application?
You cannot use $route or $router to change url, it set a new html5Â history state and reload the page. So, to change url without reloading, history.replaceState do the job. In your page or component:
methods:Â {
onClickComplete() {
if (!process.server) { // I'm not sure it's necessary
history.replaceState({}, null, window.location + '?filter=complete') // or use your own application logic: globalSiteUrl, $route... or queryString some vars...
}
}
}
At first you should change your route with "$route.push" or click on
these ways change the route without reloading
After than you can use "pages watchquery" to handle event of changing route
https://nuxtjs.org/api/pages-watchquery/
first create this helper function
export function getAbsoluteUrl(to) {
const path = $nuxt.$router.resolve(to).href
return window.location.origin + path
}
this is example for my tabs
watch: {
tab(value) {
if (!process.server) {
const url = getAbsoluteUrl({
params: { ...this.$route.params, activeTab: value }
})
history.replaceState({}, null, url) // or use your own application logic: globalSiteUrl, $route... or queryString some vars...
}
}
},
For an implementation of Magnific Popup, I need to pass a post id to the ajax settings. The post id is stored in a data attribute of the element to which Magnific Popup is bound. I would like this to work:
html element:
<a data-id="412">Clicke me</a>
Javascript:
$('.element a').magnificPopup({
type: 'ajax',
ajax: {
settings: {
url: php_array.admin_ajax,
type: 'POST',
data: ({
action:'theme_post_example',
id: postId
})
}
}
});
Where postId is read from the data attribute.
Thanks in advance.
$('.element a').magnificPopup({
callbacks: {
elementParse: function(item){
postData = {
action :'theme_post_example',
id : $(item.el[0]).attr('data-id')
}
var mp = $.magnificPopup.instance;
mp.st.ajax.settings.data = postData;
}
},
type: 'ajax',
ajax: {
settings: {
url: php_array.admin_ajax,
type: 'POST'
}
}
});
Here is how to do it:
html:
<a class="modal" data-id="412" data-action="theme_post_example">Click me</a>
jquery:
$('a.modal').magnificPopup({
type: 'ajax',
ajax: {
settings: {
url : php_array.admin_ajax,
dataType : 'json'
}
},
callbacks: {
elementParse: function() {
this.st.ajax.settings.data = {
action : this.st.el.attr('data-action'),
id : this.st.el.attr('data-id')
}
}
},
parseAjax: function( response )
{
response.data = response.data.html;
}
});
php
function theme_post_example()
{
$id = isset( $_GET['id'] ) ? $_GET['id'] : false;
$html = '<div class="white-popup mfp-with-anim">';
/**
* generate your $html code here ...
*/
$html .= '</div>';
echo json_encode( array( "html" => $html ) );
die();
}
As this answer was the original question regarding inserting data into Magnific's ajax call, I'll post this here.
After many hours of trying to figure this out, you should know that if you're using a gallery with the ability to move between gallery items without closing the popup, using elementParse to set your AJAX data will fail when you visit an item after already viewing it (while the popup is still open).
This is because elementParse is wrapped up in a check that it makes detect if an item has already been 'parsed'. Here's a small explanation as to what happens:
Open gallery at item index 2.
Item has not been parsed yet, so it sets the parsed flag to true and runs the elementParse callback (in that order). Your callback sets the ajax options to fetch this item's data, all is well.
Move (right) to item index 3.
Same as above. The item has not been parsed, so it runs the callback. Your callback sets the data. It works.
Move (left) back to item index 2.
This time the item has been parsed. It skips re-parsing the item's element for assumed potential performance reasons.Your callback is not executed. Magnific's ajax data settings will remain the same as if it were item index 3.
The AJAX call is executed with the old settings, it returns with item index 3's data instead, which is rendered to the user. Magnific will believe it is on index 2, but it is rendering index 3's data.
To resolve this, you need to hook onto a callback which is always executed pre-ajax call, like beforeChange.
The main difference is that the current item isn't passed through into the callback. Fortunately, at this point, magnific has updated their pointers to the correct index. You need to fetch the current item's element by using:
var data = {}; // Your key-value data object for jQuery's $.ajax call.
// For non-closures, you can reference mfp's instance using
// $.magnificPopup.instance instead of 'this'.
// e.g.
// var mfp = $.magnificPopup.instance;
// var itemElement = mfp.items[mfp.index].el;
var itemElement = this.items[this.index].el;
// Set the ajax data settings directly.
if(typeof this.st.ajax.settings !== 'object') {
this.st.ajax.settings = {};
}
this.st.ajax.settings.data = data;
This answer can also be used as a suitable alternative to the currently highest voted, as it will work either way.
You may use open public method to open popup dynamically http://dimsemenov.com/plugins/magnific-popup/documentation.html#public_methods
postId = $(this).attr('data-id')
$(this) retrieve the current element (the link you clicked on), and attr the value of the specified attribute.
I want to use different navigator buttons in jqGrid depending on login status.
for example: if the user is logged in then add/delete/edit button appeared.
Any ideas?
Thanks in advance.
It is possible to add buttons programmatically using the navButtonAdd method (for the navigation bar) and the toolbarButtonAdd method for the toolbar. For example:
jQuery("#grid").toolbarButtonAdd('#t_meters',{caption:"MyButton",
id: "t_my_button",
title: "Do my button action",
buttonicon: 'ui-icon-edit',
onClickButton:function(){
// Button handle code goes here...
}
});
And:
jQuery("#grid")..navButtonAdd('#pager',{
id: "t_my_button",
title: "Do my button action",
buttonicon: 'ui-icon-edit',
onClickButton:function(){
// Button handle code goes here...
}
});
For more information see the Custom Buttons on the Wiki.
Anyway, once this code is in place, you can detect login status server-side. Then use this knowledge to generate client code that only adds the buttons to your grid if the user is supposed to have access to them.
You can also use for example userdata (see http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#user_data) to send information about buttons which you need to have in the navigator. userdata should be set by server. Then with respect of:
var navGridParams = jQuery("grid_id").getGridParam('userData');
// var navGridParams = { edit: false, add: false, search: true }
you can get the data set by the server.
Now the typical call like:
jQuery("grid_id").navGrid('#pager', { edit: false, add: false, search: true });
You should place not after creating of jqGrid, but inside of than inside of loadComplete. So the code could looks like following:
var isNavCreated = false;
jQuery('#list').jqGrid({
// ...
loadComplete: function () {
var grid = jQuery("grid_id");
if (isNavCreated === false) {
isNavCreated = true;
var navGridParams = grid.getGridParam('userData');
grid.navGrid('#pager', navGridParams);
}
},
// ...
});
Another option that I see, is to use cookie instead of userdata to send information about navGridParams back to the client.