Developer tools: Match for Site url - javascript

I am using Dev tools with Google chrome and need to find out is the site url contains a specific string.
I am able to get Url_Str correctly, although when I run the match command it always returns a "match found".
How do I fix this?
let Url_Str = ___grecaptcha_cfg.clients[0].B.S.baseURI;
if (Url_Str.match(/*myconstant*/)) {"match found";}
Also is there a Alternate way to get the site url instead of using grecaptcha_cfg?

I managed to get it working. Thanks to Qasim # https://forum.freecodecamp.org/t/developer-tools-match-for-site-url/502817
let Url_Str = window.location.href;
let a = 0
if(/myconstant.com/.test(Url_Str) === true) {a = 1;}

Related

Firefox web extension, content script registration example not working for other websites

Documentation here:
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Examples
Code here:
https://github.com/mdn/webextensions-examples/tree/main/content-script-register
The above example from Firefox's own documentation does not appear to work as expected. Here is the main JS for the extension:
'use strict';
const hostsInput = document.querySelector("#hosts");
const codeInput = document.querySelector("#code");
const defaultHosts = "*://*.org/*";
const defaultCode = "document.body.innerHTML = '<h1>This page has been eaten</h1>'";
hostsInput.value = defaultHosts;
codeInput.value = defaultCode;
function registerScript() {
browser.runtime.sendMessage({
hosts: hostsInput.value.split(","),
code: codeInput.value
});
}
document.querySelector("#register").addEventListener('click', registerScript);
You can see the line const defaultHosts = "*://*.org/*"; which works as expected, however no matter what I do I cannot get it to work for i.e. const defaultHosts = *reddit.com/* or *://*google* etc.
Any ideas why it might be?
A match pattern must specify scheme://host/path, so the first pattern will be *://*.reddit.com/*
A match pattern's last domain cannot be *, so the second pattern cannot be fixed and you'll have to list all top-level domains explicitly (example).
P.S. Although it's also possible to use includeGlobs: ['*.google.*/'] when registering the content script in the background script, but it's a terrible workaround as it'll match the text in the wrong part of a URL like /path/ or search?parameter=value.

How can I get everything after the forward slash in my url?

When I visit my url, my script will get the current URL and store it in a variable with
var currentURL = (document.URL);
I'd like to get everything after the forward slash in my url because there will be a hash ID after the forward slash like this:
www.mysite.com/XdAs2
so this is what would be stored in my variable currentURL and I'd like to take only the XdAs2 from it and store that into another variable. In addition, I'd like to know two other things.
Is document.URL the best way to get the current URL or will I have issues with some browsers?
If I were to try to open that URL using an iframe, will document.URL still work? or must there be an address bar present containing the url? I would really appreciate answers for those questions three questions. Thank you
Here's some pseudo code:
var currentURL = (document.URL); // returns http://myplace.com/abcd
var part = currentURL.split("/")[1];
alert(part); // alerts abcd
Basically:
1) document.URL should work fine in all major browsers. For more info refer to this Mozilla Developer Network article or this SO question
2) for an iframe, you need to write something like: document.getElementById("iframe_ID").src.toString()
Using jquery, you can do he following in order to access every inch of the current URL:
www.mysite.com/XdAs2?x=123
assuming you have the following url:
1- get the url in a jQuery object
var currentUrl = $(location)
2- access everything using the following syntax
var result = currentUrl.attr('YOUR_DESIRED_PROPERTY');
some common properties:
hostname => www.mysite.com
pathname => XdAs2
search => ?x=123
I hope this may help.
If you want everything after the host, use window.location.pathname
Following on from Mohammed's answer you can do the same thing in vanilla javascript:
var urlPath = location.pathname,
urlHost = location.hostname;

how to get youtube video id from url

I am trying to check whether a url is a valid youtube video URL and get the youtube video ID from it, so far I am using a simple javascript split function in order to achieve this, however this has some minor disadvantages as youtube has multiple URL's.
I have been viewing other stackoverflow threads however all of them only support 1 specific URL which is not what I need.
I need something that matches all these URL's:
http(s)://www.youtu.be/videoID
http(s)://www.youtube.com/watch?v=videoID
(and optionally any other short URL's which the script automatically detects whether it contains a youtube video)
Any ideas which can be handled by the browser quick/efficient is greatly appreciated!
Try this:
var url = "...";
var videoid = url.match(/(?:https?:\/{2})?(?:w{3}\.)?youtu(?:be)?\.(?:com|be)(?:\/watch\?v=|\/)([^\s&]+)/);
if(videoid != null) {
console.log("video id = ",videoid[1]);
} else {
console.log("The youtube url is not valid.");
}
see regex:
/
(?:https?:\/{2})? // Optional protocol, if have, must be http:// or https://
(?:w{3}\.)? // Optional sub-domain, if have, must be www.
youtu(?:be)? // The domain. Match 'youtu' and optionally 'be'.
\.(?:com|be) // the domain-extension must be .com or .be
(?:\/watch\?v=|\/)([^\s&]+) //match the value of 'v' parameter in querystring from 'watch' directory OR after root directory, any non-space value.
/
Maybe you should look at the Youtube API and try to see if there is a way to get a videoID by parsing the URL though the API.
Look at this SO post:
Youtube API - Extract video ID
This could be quick:
var url = 'http://www.youtu.be/543221';
//http://www.youtube.com/watch?v=SNfYz6Yw0W8&feature=g-all-esi would work also
var a = url.split("v=")[1];
a = a != undefined ? a : url.split("youtu.be/")[1];
b = a.split("&")[0];
the variable c will have your id. Quick. The regex is nicer... harder to read though. I have modified my code to account for both.
There are too many kind:
latest short format: http://youtu.be/NLqAF9hrVbY
iframe: http://www.youtube.com/embed/NLqAF9hrVbY
iframe (secure): https://www.youtube.com/embed/NLqAF9hrVbY
object param: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US
object embed: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US
watch: http://www.youtube.com/watch?v=NLqAF9hrVbY
users: http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo
ytscreeningroom: http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I
any/thing/goes!: http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/2/PPS-8DMrAn4
any/subdomain/too: http://gdata.youtube.com/feeds/api/videos/NLqAF9hrVbY
more params: http://www.youtube.com/watch?v=spDj54kf-vY&feature=g-vrec
query may have dot: http://www.youtube.com/watch?v=spDj54kf-vY&feature=youtu.be
(Source: How do I find all YouTube video ids in a string using a regex?)
The best way is limiting input-data.
Good luck
try this code
var url = "...";
var videoid = url.match((?:youtube(?:-nocookie)?\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11}));
if(videoid != null) {
console.log("video id = ",videoid[1]);
} else {
console.log("The youtube url is not valid.");
}
The Regex is from
YouTube video ID regex
you can do it easily using preg_match here is the example:$url = "http://www.youtube.com/watch?v=YzOt12co4nk&feature=g-vrec";
preg_match('/v=([0-9a-zA-Z]+)/', $url, $matches);
$vid = $matches[1];
Now you will have the video id as: $vid = YzOt12co4nk;
I found a simple way of doing it without using regex.
I made a function which does it for you:
function getLink(url){
fetch('www.youtube.com/oembed?url=' + url).then(res => {
var thumbnailUrl = res.thumbnail_url;
var id = thumbnail_url.split('vi/')[1].substring(0, 11);
return id;}
)
}
console.log(getLink(your_url));
// here replace 'your_url' with your specified youtube url.
All this does is, it uses youtube api and passes your url as an parameter, and youtube take cares of the type of the url, so you dont have to worry about it. The next thing is, the function then takes the 'thumbnail_url' data from that api, and then splits the thumbnail's url accordingly to find the ID of the video.

Mozilla (Firefox, Thunderbird) Extension: How to get extension id (from install.rdf)?

If you are developing an extension for one of the mozilla applications (e.g. Firefox, Thunderbird, etc.) you define a extension id in the install.rdf.
If for some reason you need to know the extension id e.g. to retrieve the extension dir in local file system (1) or if you want to send it to a webservice (useage statistic) etc. it would be nice to get it from the install.rdf in favour to have it hardcoded in your javascript code.
But how to access the extension id from within my extension?
1) example code:
var extId = "myspecialthunderbirdextid#mydomain.com";
var filename = "install.rdf";
var file = extManager.getInstallLocation(extId).getItemFile(extId, filename);
var fullPathToFile = file.path;
I'm fairly sure the 'hard-coded ID' should never change throughout the lifetime of an extension. That's the entire purpose of the ID: it's unique to that extension, permanently. Just store it as a constant and use that constant in your libraries. There's nothing wrong with that.
What IS bad practice is using the install.rdf, which exists for the sole purpose of... well, installing. Once the extension is developed, the install.rdf file's state is irrelevant and could well be inconsistent.
"An Install Manifest is the file an Add-on Manager-enabled XUL application uses to determine information about an add-on as it is being installed" [1]
To give it an analogy, it's like accessing the memory of a deleted object from an overflow. That object still exists in memory but it's not logically longer relevant and using its data is a really, really bad idea.
[1] https://developer.mozilla.org/en/install_manifests
Like lwburk, I don't think its available through Mozilla's API's, but I have an idea which works, but it seems like a complex hack. The basic steps are:
Set up a custom resource url to point to your extension's base directory
Read the file and parse it into XML
Pull the id out using XPath
Add the following line to your chrome.manifest file
resource packagename-base-dir chrome/../
Then we can grab and parse the file with the following code:
function myId(){
var req = new XMLHttpRequest();
// synchronous request
req.open('GET', "resource://packagename-base-dir/install.rdf", false);
req.send(null);
if( req.status !== 0){
throw("file not found");
}
var data = req.responseText;
// this is so that we can query xpath with namespaces
var nsResolver = function(prefix){
var ns = {
"rdf" : "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"em" : "http://www.mozilla.org/2004/em-rdf#"
};
return ns[prefix] || null;
};
var parser = CCIN("#mozilla.org/xmlextras/domparser;1", Ci.nsIDOMParser);
var doc = parser.parseFromString(data, "text/xml");
// you might have to change this xpath expression a bit to fit your setup
var myExtId = doc.evaluate("//em:targetApplication//em:id", doc, nsResolver,
Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE, null);
return myExtId.singleNodeValue.textContent;
}
I chose to use a XMLHttpRequest(as opposed to simply reading from a file) to retrieve the contents since in Firefox 4, extensions aren't necessarily unzipped. However, XMLHttpRequest will still work if the extension remains packed (haven't tested this, but have read about it).
Please note that resource URL's are shared by all installed extensions, so if packagename-base-dir isn't unique, you'll run into problems. You might be able to leverage Programmatically adding aliases to solve this problem.
This question prompted me to join StackOverflow tonight, and I'm looking forward participating more... I'll be seeing you guys around!
As Firefox now just uses Chrome's WebExtension API, you can use #serg's answer at How to get my extension's id from JavaScript?:
You can get it like this (no extra permissions required) in two
different ways:
Using runtime api: var myid = chrome.runtime.id;
Using i18n api: var myid = chrome.i18n.getMessage("##extension_id");
I can't prove a negative, but I've done some research and I don't think this is possible. Evidence:
This question, which shows that
the nsIExtensionManager interface
expects you to retrieve extension
information by ID
The full nsIExtensionManager interface
description, which shows no
method that helps
The interface does allow you to retrieve a full list of installed extensions, so it's possible to retrieve information about your extension using something other than the ID. See this code, for example:
var em = Cc['#mozilla.org/extensions/manager;1']
.getService(Ci.nsIExtensionManager);
const nsIUpdateItem = Ci.nsIUpdateItem;
var extension_type = nsIUpdateItem.TYPE_EXTENSION;
items = em.getItemList(extension_type, {});
items.forEach(function(item, index, array) {
alert(item.name + " / " + item.id + " version: " + item.version);
});
But you'd still be relying on hardcoded properties, of which the ID is the only one guaranteed to be unique.
Take a look on this add-on, maybe its author could help you, or yourself can figure out:
[Extension Manager] Extended is very
simple to use. After installing, just
open the extension manager by going to
Tools and the clicking Extensions. You
will now see next to each extension
the id of that extension.
(Not compatible yet with Firefox 4.0)
https://addons.mozilla.org/firefox/addon/2195

How do I get the referrer's domain/host name using JavaScript?

I know I can get the host name of the current page, by simply doing:
var myhostname = location.hostname;
But how do I get the host name of the referrer? I can get the referrer by
var referrer = document.referrer;
but unfortunately there's no document.referrer.hostname available in JavaScript. How can I get this value?
An example of where this is useful is if somebody clicks a link on google.com. I want to be able to retrieve google.com from the referrer (not the page and the query string).
This would do:
document.referrer.split('/')[2];
Example.
function parseURL(url) {
var a=document.createElement('a');
a.href=url;
return a.hostname;
}
This is a relatively old question, nevertheless this may help any followers.
By parsing it. document.referrer.split( '/' ); will get you close. Or take a look at this
http://blog.stevenlevithan.com/archives/parseuri
If referrer is coming from a browser, it will be sane -- but just in case you want more robust parsing.
You can use var referrer = new URL(document.referrer).hostname.
See https://developer.mozilla.org/en-US/docs/Web/API/URL.URL.
You can use regexp to extract this data.
string.match(/^http([s]?)://([a-zA-Z0-9-_\.]+)(:[0-9]+)?/);
Hi use this function to get domain name.
function getDomain(url) {
if (url) {
var match = /(?:https?:\/\/)?(?:\w+:\/)?[^:?#\/\s]*?([^.\s]+\.(?:[a-z]{2,}|co\.uk|org\.uk|ac\.uk|org\.au|com\.au))(?:[:?#\/]|$)/gi
.exec(url);
return match ? match[1] : null;
} else
return null;
}
It includes the protocol, but document.origin will work. It works via the Origin header, which has no path information included with it.

Categories

Resources