TL;DR: How can I access the audio instances created in the callback of createAdio?
I have the following code in my p5 sketch
// in preload
sound_a = createAudio('sound_a.mp3');
// in setup
sound_a.loop();
sound_a.volume(0.2);
sound_a.play();
This does what I want it to do. However, in my current circumstances, I have multiple audio files for which I wanted to call the same functions. I would want to use a callback to apply the loop, volume and play. My intended behavior is something like this:
// in preload - this would just be a loop
sound_a = createAudio('sound_a.mp3', audio_callback);
sound_b = createAudio('sound_b.mp3', audio_callback);
.....
sound_z = createAudio('sound_z.mp3', audio_callback);
function audio_callback(audio) {
audio.loop();
audio.volume(0.2);
audio.play();
}
However, the callback is not passed any arguments (i.e., console.log(audio) returns undefined and audio.loop() throws the expected errors.). How can I access the audio created in the callback?
Whenever you're doing sound_a, sound_b, ... sound_z, you probably want an array. You can then use loops to avoid repetition and solve the problem you're having by binding an index i to each sound:
const urls = [
"https://upload.wikimedia.org/wikipedia/commons/f/f7/BILIIE_EILISH.ogg",
"https://upload.wikimedia.org/wikipedia/commons/7/7f/Bluetooth.ogg",
"https://upload.wikimedia.org/wikipedia/commons/8/8d/Bismarck71_English_Voice_Sample_%28North_Wind_%26_Sun%29.ogg",
];
let sounds;
function preload() {
sounds = urls.map((url, i) =>
createAudio(url, () => {
sounds[i].volume(0.2);
// prohibited due to autoplay policy
// sounds[i].loop();
// sounds[i].play();
})
);
}
function setup() {}
function mousePressed() {
sounds.forEach(e => {
e.loop();
e.play();
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>
<h1>Click anywhere to play</h1>
<h4>File attribution:</h4>
<p>
Laidaiturrate, CC BY-SA 4.0, via Wikimedia Commons
</p>
<p>
Sorondo27, CC BY-SA 4.0, via Wikimedia Commons
</p>
<p>
Bismarck71, CC BY-SA 4.0, via Wikimedia Commons
</p>
You could also put the audio object in a data structure alongside each sound rather than in a separate array:
const sounds = [
{url: "https://upload.wikimedia.org/wikipedia/commons/f/f7/BILIIE_EILISH.ogg"},
{url: "https://upload.wikimedia.org/wikipedia/commons/7/7f/Bluetooth.ogg"},
{url: "https://upload.wikimedia.org/wikipedia/commons/8/8d/Bismarck71_English_Voice_Sample_%28North_Wind_%26_Sun%29.ogg"},
];
function preload() {
sounds.forEach(e => {
e.audio = createAudio(e.url, () => {
e.audio.volume(0.2);
// prohibited due to autoplay policy
// e.audio.loop();
// e.audio.play();
})
});
}
function setup() {}
function mousePressed() {
sounds.forEach(e => {
e.audio.loop();
e.audio.play();
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>
<h1>Click anywhere to play</h1>
<h4>File attribution:</h4>
<p>
Laidaiturrate, CC BY-SA 4.0, via Wikimedia Commons
</p>
<p>
Sorondo27, CC BY-SA 4.0, via Wikimedia Commons
</p>
<p>
Bismarck71, CC BY-SA 4.0, via Wikimedia Commons
</p>
You might wish to open an issue or a PR for implementing the audio as a parameter to the callback.
Related
I found this (github) html starter page for google auth, and I wanted to make it into a astro component. Im wanted to convert this to a .astro file and be able to pass in the variables for CLIENT_ID and API_KEY from the backend. I
Here's the HTML code from google:
<!DOCTYPE html>
<html>
<head>
<title>Google Calendar API Quickstart</title>
<meta charset="utf-8" />
</head>
<body>
<p>Google Calendar API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
<button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
/* exported gapiLoaded */
/* exported gisLoaded */
/* exported handleAuthClick */
/* exported handleSignoutClick */
// TODO(developer): Set to client ID and API key from the Developer Console
const CLIENT_ID = '<YOUR_CLIENT_ID>';
const API_KEY = '<YOUR_API_KEY>';
// Discovery doc URL for APIs used by the quickstart
const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest';
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
const SCOPES = 'https://www.googleapis.com/auth/calendar.readonly';
let tokenClient;
let gapiInited = false;
let gisInited = false;
document.getElementById('authorize_button').style.visibility = 'hidden';
document.getElementById('signout_button').style.visibility = 'hidden';
/**
* Callback after api.js is loaded.
*/
function gapiLoaded() {
gapi.load('client', intializeGapiClient);
}
/**
* Callback after the API client is loaded. Loads the
* discovery doc to initialize the API.
*/
async function intializeGapiClient() {
await gapi.client.init({
apiKey: API_KEY,
discoveryDocs: [DISCOVERY_DOC],
});
gapiInited = true;
maybeEnableButtons();
}
/**
* Callback after Google Identity Services are loaded.
*/
function gisLoaded() {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: '', // defined later
});
gisInited = true;
maybeEnableButtons();
}
/**
* Enables user interaction after all libraries are loaded.
*/
function maybeEnableButtons() {
if (gapiInited && gisInited) {
document.getElementById('authorize_button').style.visibility = 'visible';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick() {
tokenClient.callback = async (resp) => {
if (resp.error !== undefined) {
throw (resp);
}
document.getElementById('signout_button').style.visibility = 'visible';
document.getElementById('authorize_button').innerText = 'Refresh';
await listUpcomingEvents();
};
if (gapi.client.getToken() === null) {
// Prompt the user to select a Google Account and ask for consent to share their data
// when establishing a new session.
tokenClient.requestAccessToken({prompt: 'consent'});
} else {
// Skip display of account chooser and consent dialog for an existing session.
tokenClient.requestAccessToken({prompt: ''});
}
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick() {
const token = gapi.client.getToken();
if (token !== null) {
google.accounts.oauth2.revoke(token.access_token);
gapi.client.setToken('');
document.getElementById('content').innerText = '';
document.getElementById('authorize_button').innerText = 'Authorize';
document.getElementById('signout_button').style.visibility = 'hidden';
}
}
/**
* Print the summary and start datetime/date of the next ten events in
* the authorized user's calendar. If no events are found an
* appropriate message is printed.
*/
async function listUpcomingEvents() {
let response;
try {
const request = {
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime',
};
response = await gapi.client.calendar.events.list(request);
} catch (err) {
document.getElementById('content').innerText = err.message;
return;
}
const events = response.result.items;
if (!events || events.length == 0) {
document.getElementById('content').innerText = 'No events found.';
return;
}
// Flatten to string to display
const output = events.reduce(
(str, event) => `${str}${event.summary} (${event.start.dateTime || event.start.date})\n`,
'Events:\n');
document.getElementById('content').innerText = output;
}
</script>
<script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
<script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
</body>
</html>
I quickly found there's no way to template these variables into the <script> tag. I tried attaching the variables to window and other sneaky things nothing worked.
You can share the server variables to client side by defining define:vars attribute on <script /> or <style /> tag in the .astro template.
Read the astro documentation here for more information.
Example as below ( source : Astro documentation )
---
const foregroundColor = "rgb(221 243 228)"; // CSS variable shared
const backgroundColor = "rgb(24 121 78)"; // CSS variable shared
const message = "Astro is awesome!"; // Javascript variable shared
---
/* +++++ CSS variables to share as below +++++ */
<style define:vars={{ textColor: foregroundColor, backgroundColor }}>
h1 {
background-color: var(--backgroundColor);
color: var(--textColor);
}
</style>
/* ++++ Javascript variables to share as below ++++ */
<script define:vars={{ message }}>
alert(message);
</script>
There is also a concept of sharing states using nanostore stated in documentation . It
allows sharing states between components at framework level on
client-side. Not between client and server.
Theoretically sharing states from server to client can be done using
hydration technique by combining define:vars and nanostore
library map api during the onLoad event may be 🧪.
I came up with this sneaky way of doing it but 🤮
---
interface Props {
clientId: string,
apiKey: string
}
const { clientId, apiKey } = Astro.props as Props;
---
<!-- begining code -->
<div id="clientId" style="display:none">{clientId}</div>
<div id="apiKey" style="display:none">{apiKey}</div>
<script type="text/javascript">
/* exported gapiLoaded */
/* exported gisLoaded */
/* exported handleAuthClick */
/* exported handleSignoutClick */
// TODO(developer): Set to client ID and API key from the Developer Console
const CLIENT_ID = document.getElementById('clientId').innerText;
const API_KEY = document.getElementById('apiKey').innerText;
console.log({ CLIENT_ID, API_KEY })
// ... rest of the code
You can access a file with import.meta.glob(), and from the file you can get the variable you want.
/index.astro:
---
//Node stuff
---
<html>
//template here
</html>
<script>
const modules = import.meta.glob('./blog/*.{md,mdx}')
for (const path in modules) {
modules[path]().then((mod) => {
console.log(path, mod) //Access fronttmatter, content, path, etc
})
</script>
I need the environment variable in a function that is binded to an onclick so I came up with following hacky quite ugly workaround today. Using vars too but by assiging the value to the window object.
---
const code = import.meta.env.PUBLIC_CODE;
---
<script is:inline define:vars={{ code }}>
window.code = code;
</script>
<script is:inline>
const copy = async () => await navigator.clipboard.writeText(window.code);
</script>
<button onclick="copy()">
Copy
</button>
I welcome any better solution!
Server to Client with Astro
frontmatter variable in html attribute or content
define:vars but not always recommended
cookies
Server Sent Events
Websockets
Database
I only posted points, because this question only adresses one path, server->client, and not the whole scenario server<->client. For a detailed answer about State sharing including server to client see How to share state among components in Astro?
Is there a way to write a google apps script so when ran, a second browser window opens to www.google.com (or another site of my choice)?
I am trying to come up with a work-around to my previous question here:
Can I add a hyperlink inside a message box of a Google Apps spreadsheet
This function opens a URL without requiring additional user interaction.
/**
* Open a URL in a new tab.
*/
function openUrl( url ){
var html = HtmlService.createHtmlOutput('<html><script>'
+'window.close = function(){window.setTimeout(function(){google.script.host.close()},9)};'
+'var a = document.createElement("a"); a.href="'+url+'"; a.target="_blank";'
+'if(document.createEvent){'
+' var event=document.createEvent("MouseEvents");'
+' if(navigator.userAgent.toLowerCase().indexOf("firefox")>-1){window.document.body.append(a)}'
+' event.initEvent("click",true,true); a.dispatchEvent(event);'
+'}else{ a.click() }'
+'close();'
+'</script>'
// Offer URL as clickable link in case above code fails.
+'<body style="word-break:break-word;font-family:sans-serif;">Failed to open automatically. Click here to proceed.</body>'
+'<script>google.script.host.setHeight(40);google.script.host.setWidth(410)</script>'
+'</html>')
.setWidth( 90 ).setHeight( 1 );
SpreadsheetApp.getUi().showModalDialog( html, "Opening ..." );
}
This method works by creating a temporary dialog box, so it will not work in contexts where the UI service is not accessible, such as the script editor or a custom G Sheets formula.
You can build a small UI that does the job like this :
function test(){
showURL("http://www.google.com")
}
//
function showURL(href){
var app = UiApp.createApplication().setHeight(50).setWidth(200);
app.setTitle("Show URL");
var link = app.createAnchor('open ', href).setId("link");
app.add(link);
var doc = SpreadsheetApp.getActive();
doc.show(app);
}
If you want to 'show' the URL, just change this line like this :
var link = app.createAnchor(href, href).setId("link");
EDIT : link to a demo spreadsheet in read only because too many people keep writing unwanted things on it (just make a copy to use instead).
EDIT : UiApp was deprecated by Google on 11th Dec 2014, this method could break at any time and needs updating to use HTML service instead!
EDIT :
below is an implementation using html service.
function testNew(){
showAnchor('Stackoverflow','http://stackoverflow.com/questions/tagged/google-apps-script');
}
function showAnchor(name,url) {
var html = '<html><body>'+name+'</body></html>';
var ui = HtmlService.createHtmlOutput(html)
SpreadsheetApp.getUi().showModelessDialog(ui,"demo");
}
There really isn't a need to create a custom click event as suggested in the bountied answer or to show the url as suggested in the accepted answer.
window.open(url)1 does open web pages automatically without user interaction, provided pop- up blockers are disabled(as is the case with Stephen's answer)
openUrl.html
<!DOCTYPE html>
<html>
<head>
<base target="_blank">
<script>
const url1 ='https://stackoverflow.com/a/54675103';
const winRef = window.open(url1);
winRef ? google.script.host.close() : window.alert('Allow popup to redirect you to '+url1) ;
window.onload=function(){document.getElementById('url').href = url1;}
</script>
</head>
<body>
Kindly allow pop ups</br>
Or <a id='url'>Click here </a>to continue!!!
</body>
</html>
code.gs:
function modalUrl(){
SpreadsheetApp.getUi()
.showModalDialog(
HtmlService.createHtmlOutputFromFile('openUrl').setHeight(50),
'Opening StackOverflow'
)
}
Google Apps Script will not open automatically web pages, but it could be used to display a message with links, buttons that the user could click on them to open the desired web pages or even to use the Window object and methods like addEventListener() to open URLs.
It's worth to note that UiApp is now deprecated. From Class UiApp - Google Apps Script - Google Developers
Deprecated. The UI service was deprecated on December 11, 2014. To
create user interfaces, use the HTML service instead.
The example in the HTML Service linked page is pretty simple,
Code.gs
// Use this code for Google Docs, Forms, or new Sheets.
function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.createMenu('Dialog')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
.showModalDialog(html, 'Dialog title');
}
A customized version of index.html to show two hyperlinks
<a href='http://stackoverflow.com' target='_blank'>Stack Overflow</a>
<br/>
<a href='http://meta.stackoverflow.com/' target='_blank'>Meta Stack Overflow</a>
Building of off an earlier example, I think there is a cleaner way of doing this. Create an index.html file in your project and using Stephen's code from above, just convert it into an HTML doc.
<!DOCTYPE html>
<html>
<base target="_top">
<script>
function onSuccess(url) {
var a = document.createElement("a");
a.href = url;
a.target = "_blank";
window.close = function () {
window.setTimeout(function() {
google.script.host.close();
}, 9);
};
if (document.createEvent) {
var event = document.createEvent("MouseEvents");
if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) {
window.document.body.append(a);
}
event.initEvent("click", true, true);
a.dispatchEvent(event);
} else {
a.click();
}
close();
}
function onFailure(url) {
var div = document.getElementById('failureContent');
var link = 'Process';
div.innerHtml = "Failure to open automatically: " + link;
}
google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).getUrl();
</script>
<body>
<div id="failureContent"></div>
</body>
<script>
google.script.host.setHeight(40);
google.script.host.setWidth(410);
</script>
</html>
Then, in your Code.gs script, you can have something like the following,
function getUrl() {
return 'http://whatever.com';
}
function openUrl() {
var html = HtmlService.createHtmlOutputFromFile("index");
html.setWidth(90).setHeight(1);
var ui = SpreadsheetApp.getUi().showModalDialog(html, "Opening ..." );
}
I liked #Stephen M. Harris's answer, and it worked for me until recently. I'm not sure why it stopped working.
What works for me now on 2021-09-01:
function openUrl( url ){
Logger.log('openUrl. url: ' + url);
const html = `<html>
<a id='url' href="${url}">Click here</a>
<script>
var winRef = window.open("${url}");
winRef ? google.script.host.close() : window.alert('Configure browser to allow popup to redirect you to ${url}') ;
</script>
</html>`;
Logger.log('openUrl. html: ' + html);
var htmlOutput = HtmlService.createHtmlOutput(html).setWidth( 250 ).setHeight( 300 );
Logger.log('openUrl. htmlOutput: ' + htmlOutput);
SpreadsheetApp.getUi().showModalDialog( htmlOutput, `openUrl function in generic.gs is now opening a URL...` ); // https://developers.google.com/apps-script/reference/base/ui#showModalDialog(Object,String) Requires authorization with this scope: https://www.googleapis.com/auth/script.container.ui See https://developers.google.com/apps-script/concepts/scopes#setting_explicit_scopes
}
https://developers.google.com/apps-script/reference/base/ui#showModalDialog(Object,String) Requires authorization with this scope: https://www.googleapis.com/auth/script.container.ui See https://developers.google.com/apps-script/concepts/scopes#setting_explicit_scopes
In Angular is it possible to grab data from an AJAX call, and translate it into HTML that is put into a Directive template?
Here is a Pseudo Example below:
App.directive('aDirective', function (){
var getTemplate = function() {
var template = '';
//Make Ajax call here
...
angular.forEach(content_from_ajax, function (data) {
template += '<li>data</li>';
});
return template;
}
return {
restrict: "E",
template: getTemplate();
};
});
HTML:
<ul>
<a-directive></a-directive>
</ul>
This example would show an arbitrary length list.
How would I go on doing this?
Just because you are writing a directive, you shouldn't forget how normal Angular things, like templating based on data, are done.
In other words, you seem to receive an array of data from the backend, and you want to render the data in a list. Isn't it the perfect job for an ng-repeat?
App.directive('aDirective', function (AjaxService){
return {
restrict: "E",
template: '<li ng-repeat="item in content_from_ajax">{{item}}</li>',
link: function(scope){
// AjaxService here is a standin to how you get data from the backend
AjaxService.getData()
.then(function(data){
scope.content_from_ajax = data;
});
}
});
The ng-repeat would just work normally - i.e. iterate over the data and produce a template.
Also, template or templateUrl properties of the directive definition object do not support async operations, so your entire idea of asynchronously fetching a template in getTemplate and then using the result with template: getTemplate() would not have worked.
I am new to the whole front-end client scripting scene and have encountered a few difficulties when working on my most recent project. I have looked around the website and could not find anything that answered my question. There may be something here and I have just not found it because of my inexperience and if there is it would be nice if you can provide a link to those resources.
I am currently working on building a client that makes ajax calls to a cross-domain asp.net web api that I have built. I know that the web api works as it has been tested in fiddler. I have also managed to successfully make calls on a click event.
The problem is that I cannot seem to get this working on page load and with knockoutjs. I have tried to do a simple list that is populated with data when the page loads but when I load the page and check fiddler I can see that the ajax calls are not being made. This possibly explains why when I load the page the content isn't there. I have tried inserting some static data to view model and the binding worked so it seems it may be the case that there is something blocking the ajax calls.
I have looked at examples and have knocked up some code. I cannot see any problems with the code but as I am inexperienced there is certainly a possibility that I am missing something. There may also be more efficient ways to do model binding, if so, I would appreciate any advice from someone more experienced.
The code is:
#{
ViewBag.Title = "KnockoutTesting";
}
<!-- MAIN -->
<div id="main">
<!-- wrapper-main -->
<div class="wrapper">
<ul data-bind="foreach: places">
<li>
<span data-bind="text: title"></span>
</li>
</ul>
</div>
</div>
#section scripts {
<script type="text/javascript" src="../../Scripts/jquery-1.7.2.js"></script>
<script type="text/javascript" src="../../Scripts/knockout-2.1.0.js"></script>
<script type="text/javascript">
function PlacesViewModel() {
var self = this;
function Place(root, id, title, description, url, pub) {
var self = this;
self.id = id;
self.title = ko.observable(title);
self.description = ko.observable(description);
self.url = ko.observable(url);
self.pub = ko.observable(pub);
self.remove = function () {
root.sendDelete(self);
};
self.update = function (title, description, url, pub) {
self.title(title);
self.description(description);
self.url(url);
self.pub(pub);
};
};
self.places = ko.observableArray();
self.add = function (id, title, description, url, pub) {
self.places.push(new Place(self, id, title, description, url, pub));
};
self.remove = function (id) {
self.places.remove(function (place) { return place.id === id; });
};
self.update = function (id, title, description, url, pub) {
var oldItem = ko.utils.arrayFirst(self.places(), function (i) { return i.id === id; });
if (oldItem) {
oldItem.update(title, description, url, pub);
}
};
self.sendDelete = function (place) {
$.ajax({
url: "http://localhost:1357/api/places" + place.id,
type: "DELETE"
});
}
};
$(function () {
var viewModel = new PlacesViewModel();
ko.applyBindings(viewModel);
$JQuery.support.cors = true;
$.get("http://localhost:1357/api/places", function (places) {
$.each(places, function (idx, place) {
viewModel.add(place.PlaceID, place.Title, place.Description, place.URL, place.Public);
});
}, "json");
});
</script>
}
It has been simplified for the sake of getting it to work before I add more functionality.
Thanks for your time.
I believe your problem may lie in your Web API implementation. Both the client and the server must support CORS. According to Carlos' post, Web API does not natively support CORS. His post includes a code sample.
I'm writing a sidebar extension for Firefox and need a way to get the URL of the current page so I can check it against a database and display the results. How can I do this?
I stumbled over this post while looking for an answer to the same question.
Actually I think it's as easy as
alert(window.content.location.href)
See also https://developer.mozilla.org/en/DOM/window.content
window.top.getBrowser().selectedBrowser.contentWindow.location.href;
might work, otherwise I think you need to use:
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
mainWindow.getBrowser().selectedBrowser.contentWindow.location.href;
This seems to work fine for me
function getCurrentURL(){
var currentWindow = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
var currBrowser = currentWindow.getBrowser();
var currURL = currBrowser.currentURI.spec;
return currURL;
}
https://developer.mozilla.org/En/Working_with_windows_in_chrome_code
If you need to access the main browser from the code running in a sidebar, you'll something like what Wimmel posted, except the last line could be simplified to
mainWindow.content.location.href
(alternatively you could use 's API returning an nsIURI).
Depending on your task, it might make sense to run the code in the browser window instead (e.g. in a page load handler), then it can access the current page via the content shortcut and the sidebar via document.getElementById("sidebar").contentDocument or .contentWindow.
If you need only domain and subdomain;
Usage;
PageDomain.getDomain(); // stackoverflow.com
PageDomain.getSubDomain(); // abc.stackoverflow.com
Code;
PageDomain = {
getDomain : function() {
var docum = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
var domain = PageDomain.extractDomain(new String(docum.location));
return domain;
},
getSubDomain : function() {
var docum = Components.classes["#mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator).getMostRecentWindow("navigator:browser");
var subDomain = PageDomain.extractSubDomain(new String(docum.location));
return subDomain;
},
extractDomain: function(host) {
var s;
// Credits to Chris Zarate
host=host.replace('http:\/\/','');
host=host.replace('https:\/\/','');
re=new RegExp("([^/]+)");
host=host.match(re)[1];
host=host.split('.');
if(host[2]!=null) {
s=host[host.length-2]+'.'+host[host.length-1];
domains='ab.ca|ac.ac|ac.at|ac.be|ac.cn|ac.il|ac.in|ac.jp|ac.kr|ac.nz|ac.th|ac.uk|ac.za|adm.br|adv.br|agro.pl|ah.cn|aid.pl|alt.za|am.br|arq.br|art.br|arts.ro|asn.au|asso.fr|asso.mc|atm.pl|auto.pl|bbs.tr|bc.ca|bio.br|biz.pl|bj.cn|br.com|cn.com|cng.br|cnt.br|co.ac|co.at|co.il|co.in|co.jp|co.kr|co.nz|co.th|co.uk|co.za|com.au|com.br|com.cn|com.ec|com.fr|com.hk|com.mm|com.mx|com.pl|com.ro|com.ru|com.sg|com.tr|com.tw|cq.cn|cri.nz|de.com|ecn.br|edu.au|edu.cn|edu.hk|edu.mm|edu.mx|edu.pl|edu.tr|edu.za|eng.br|ernet.in|esp.br|etc.br|eti.br|eu.com|eu.lv|fin.ec|firm.ro|fm.br|fot.br|fst.br|g12.br|gb.com|gb.net|gd.cn|gen.nz|gmina.pl|go.jp|go.kr|go.th|gob.mx|gov.br|gov.cn|gov.ec|gov.il|gov.in|gov.mm|gov.mx|gov.sg|gov.tr|gov.za|govt.nz|gs.cn|gsm.pl|gv.ac|gv.at|gx.cn|gz.cn|hb.cn|he.cn|hi.cn|hk.cn|hl.cn|hn.cn|hu.com|idv.tw|ind.br|inf.br|info.pl|info.ro|iwi.nz|jl.cn|jor.br|jpn.com|js.cn|k12.il|k12.tr|lel.br|ln.cn|ltd.uk|mail.pl|maori.nz|mb.ca|me.uk|med.br|med.ec|media.pl|mi.th|miasta.pl|mil.br|mil.ec|mil.nz|mil.pl|mil.tr|mil.za|mo.cn|muni.il|nb.ca|ne.jp|ne.kr|net.au|net.br|net.cn|net.ec|net.hk|net.il|net.in|net.mm|net.mx|net.nz|net.pl|net.ru|net.sg|net.th|net.tr|net.tw|net.za|nf.ca|ngo.za|nm.cn|nm.kr|no.com|nom.br|nom.pl|nom.ro|nom.za|ns.ca|nt.ca|nt.ro|ntr.br|nx.cn|odo.br|on.ca|or.ac|or.at|or.jp|or.kr|or.th|org.au|org.br|org.cn|org.ec|org.hk|org.il|org.mm|org.mx|org.nz|org.pl|org.ro|org.ru|org.sg|org.tr|org.tw|org.uk|org.za|pc.pl|pe.ca|plc.uk|ppg.br|presse.fr|priv.pl|pro.br|psc.br|psi.br|qc.ca|qc.com|qh.cn|re.kr|realestate.pl|rec.br|rec.ro|rel.pl|res.in|ru.com|sa.com|sc.cn|school.nz|school.za|se.com|se.net|sh.cn|shop.pl|sk.ca|sklep.pl|slg.br|sn.cn|sos.pl|store.ro|targi.pl|tj.cn|tm.fr|tm.mc|tm.pl|tm.ro|tm.za|tmp.br|tourism.pl|travel.pl|tur.br|turystyka.pl|tv.br|tw.cn|uk.co|uk.com|uk.net|us.com|uy.com|vet.br|web.za|web.com|www.ro|xj.cn|xz.cn|yk.ca|yn.cn|za.com';
domains=domains.split('|');
for(var i=0;i<domains.length;i++) {
if(s==domains[i]) {
s=host[host.length-3]+'.'+s;
break;
}
}
} else {
s=host.join('.');
}
// Thanks Chris
return s;
},
extractSubDomain:function(host){
host=host.replace('http:\/\/','');
host=host.replace('https:\/\/','');
re=new RegExp("([^/]+)");
host=host.match(re)[1];
return host;
}
}
From a Firefox extension popup ;
You'll need
"permissions": [
"activeTab"
]
in your manifest or possibly tabs instead of activeTab
async function getCurrentTabUrl(){
let tabs = await browser.tabs.query({active: true, currentWindow: true}) ;
return tabs[0].url ;
}
let hostUrl = await getCurrentTab();
alert(hostUrl);
This works from a firefox "popup" extension.
browser.tabs.query({active: true, windowId: browser.windows.WINDOW_ID_CURRENT})
.then(tabs => browser.tabs.get(tabs[0].id))
.then(tab => {
console.log(tab);
});
Hallo,
I have tried to implement this in JavaScript, because I need that in my project too, but all three possible solutions didn't work. I have also implemented a small site to test it, but this also didn't work.
Here is the source code of the small site:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function Fall1 () {
alert(window.top.getBrowser().selectedBrowser.contentWindow.location.href);
}
function Fall2() {
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
alert(mainWindow.getBrowser().selectedBrowser.contentWindow.location.href);
}
function Fall3() {
alert(document.getElementById("sidebar").contentWindow.location.href);
}
</script>
</head>
<body>
<form name="Probe" action="">
<input type="button" value="Fall1"
onclick="Fall1()">
<input type="button" value="Fall2"
onclick="Fall2()">
<input type="button" value="Fall3"
onclick="Fall13()">
</form>
</body>
</html>