Chrome Extension – Get Current Or Active Tab Id And URL

Chrome Extension – Get Current Or Active Tab Id And URL

Here’s a quick code snippet on how you can get your current tab details when developing a chrome plugin or extension.

To get current tab id,

var tabId = chrome.tabs.getSelected(null, function(tab) {
    var tabId = tab.id;
    
    return tabId;
});

To get current tab url,

var tabUrl = chrome.tabs.getSelected(null, function(tab) {
    var tabUrl = tab.url;
    
    return tabUrl;
});

That’s all. Let me know if you need any assistance in the comments.

Enjoyed the content ? Share it with your friends !

Autoloading in your wordpress plugin

Autoloading in your wordpress plugin

An important thing to note is that you will want your autoloader to load classes from your plugin only. If you do not enforce this restriction, your plugin may end up conflicting with WordPress or other plugins.

To enforce this restriction, simply check the classNamevariable in the autoload function for your plugin’s namespace. An example is shown below

if(strpos($className, __NAMESPACE__) !== 0)
        return;

So a simple autoloader would look like this (replace PLUGIN_PATH_HERE with your plugin’s path)

spl_autoload_register(__NAMESPACE__ . '\\autoload');
function autoload($className)
{
    $ext = '.php';
    $cls = ltrim($className, '\\');
    if(strpos($className, __NAMESPACE__) !== 0)
        return;

    $cls = str_replace(__NAMESPACE__, '', $className);
    $path = PLUGIN_PATH_HERE . str_replace('\\', DIRECTORY_SEPARATOR, $className) . $ext; // Replace PLUGIN_PATH_HERE with your plugin path
    require_once($path);
}

 

Enjoyed the content ? Share it with your friends !

WordPress the correct way to load jQuery for your plugin or theme

To load a script in wordpress, you have to use the function wp_enqueue_script

Often people call the function like this

wp_enqueue_script('my-script', get_template_directory_uri() .'/js/my-script.js');

However, you may come across dependency problems if you do it like the above. Hence, it is best practice to use the other parameters, especially the third one which specifies the dependency. For example, if your script relies on jquery,

wp_enqueue_script('my-script', get_template_directory_uri() .'/js/my-script.js', array('jquery'));

Also, you can check if jquery is already enqueued by using

if ( ! wp_script_is( 'jquery', 'enqueued' ) ) {
    wp_enqueue_script( 'jquery' );
}

Finally, note that wp_enqueue_script is for the front-end of your site. If you wish to queue scripts for the admin panel, use admin_enqueue_scripts

Enjoyed the content ? Share it with your friends !