OPEN (on click) an specific URL from a 'complex' URL - javascript

I have a complex string (URL) that is a link .
How to OPEN on click a specific URL from that URL/string... NOT the 'parent' URL?
Parent URL looks like this:
http://www.randomsite.com & randomtext & URL I need
.
Thank you.

On the assumption you mean get the url from the query string e.g. http://www.randomsite.com?foo=bar&url=http://www.url-i-want.com
You could do this:
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var url = getParameterByName('url');
window.location.href = url;
ref: https://stackoverflow.com/a/901144/905653

Here is a simple solution
function getUrlVar(stringUrl, name) {
for (var value of stringUrl.split("?")[1].split("&")) {
var valueArr = value.split("=");
if (valueArr[0] === name) {
return valueArr[1];
}
}
return false;
}
var complexUrl = "http://www.whatever.com?lang=en&url=http://www.anyurlwhatsoever.com&test=loremipsum";
console.log(getUrlVar(complexUrl, "test"));
console.log(getUrlVar(complexUrl, "lang"));
console.log(getUrlVar(complexUrl, "url"));
console.log(getUrlVar(complexUrl, "asdasd"));

...Almost done... ! ;-)
But...I will be more 'specific':
ParentURL = URL1+random-text+URL-I-want
What I want to do is...on click on the link/ParentURL to open the link/URL-I-want, NOT the link/ParentURL (I think the best "suggestion" is...to 'specify' somehow a 'part' of the URL1...to be sure the URL of the opened window will be URL-I-want, NOT the URL1) !
Thank you .
function getUrlVar(stringUrl, name) {
for (var value of stringUrl.split("?")[1].split("&")) {
var valueArr = value.split("=");
if (valueArr[0] === name) {
return valueArr[1];
}
}
return false;
}
var complexUrl = "http://www.whatever.com?lang=en&url=http://www.anyurlwhatsoever.com&test=loremipsum";
console.log(getUrlVar(complexUrl, "test"));
console.log(getUrlVar(complexUrl, "lang"));
console.log(getUrlVar(complexUrl, "url"));
console.log(getUrlVar(complexUrl, "asdasd"));

Related

Function not being run after if statement in Chrome extension

I am making a Chrome extension for version 87.0.4280.66.
It's a little fun script library to mess around with apps.
Right now, I'm making a Chrome extension that when you click a button, it adds on to an Instructure link to make it play confetti.
I'm making it check if there are parameters present or not, as well as if it is an Instructure link too.
The problem is when I call the function, it doesn't run it at all.
Here is the popup.js that is responsible for updating the URL to add the parameter confetti=true.
let confetti = document.getElementById('confetti');
const regEx = /https:\/\/cbsd\.instructure\.com\/courses\/([0-9]{5})\/assignments\/([0-9]{6})\?module_item_id=([0-9]{7})|https:\/\/cbsd\.instructure\.com\/courses\/([0-9]{5})\/assignments\/([0-9]{6})/g;
var getParams = function (url) {
var params = {};
var parser = document.createElement('a');
parser.href = url;
var query = parser.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
params[pair[0]] = decodeURIComponent(pair[1]);
}
return params;
};
function error(message)
{
var notification = {
type: "basic",
title: "Error",
iconUrl: "images/error.ico",
message: message
}
chrome.notifications.create(notification);
}
function isCanvas(domain)
{
return regEx.test(domain);
}
function isMod(dom)
{
var parameters = getParams(dom);
if (parameters) {
return(true)
} else {
return(false)
}
}
confetti.onclick = function(element) {
chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
let domain = tabs[0].url;
var canvasCheck = isCanvas(domain)
if (canvasCheck === true) {
error(isMod(domain).toString());
/*/ if (andOrQuestion) {
let newUrl = domain + "&confetti=true";
chrome.tabs.update({url: newUrl});
} else {
let newUrl = domain + "?confetti=true"
chrome.tabs.update({url: newUrl});
} /*/
} else {
// error("You are not on an assignment page!")
}
});
}
Thank you for taking the time to answer this question and have a nice day!

Get very specific url

I want to get very specific string over my url to add as parameter in js:
function cambiarContrasena(usuario, completado, fallo) {
apiService.post('/api/usuario/cambiarContrasena?token=', usuario,
completado,
fallo);
}
URL
http://localhost:55728/Cliente/#/cambiarContrasena.html?Token=e12009cf-d48d-42e7-ba43-83b5082019bb
I want to get only Guid afrer Token= like:
e12009cf-d48d-42e7-ba43-83b5082019bb
I try using:
var url = (location.pathname + location.search).substr(1);
function cambiarContrasena(usuario, completado, fallo) {
apiService.post('/api/usuario/cambiarContrasena?token='+url, usuario,
completado,
fallo);
}
But I get
http://localhost:55718/api/usuario/cambiarContrasena?token=Cliente/
I try too:
var guid = url.substr(url.indexOf('Token=') + 6);
function cambiarContrasena(usuario, completado, fallo) {
apiService.post('/api/usuario/cambiarContrasena?token='+guid, usuario,
completado,
fallo);
}
But I get
Uncaught ReferenceError: url is not defined
What I need to do to get only parameters after Token= ?
I try as this question:
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function cambiarContrasena(usuario, completado, fallo) {
apiService.post('/api/usuario/cambiarContrasena?token='+getParameterByName, usuario,
completado,
fallo);
}
But I get an error:
POST
http://localhost:55718/api/usuario/cambiarContrasena?token=function%20getPa…%20%20var%20regex%20=%20new%20RegExp(%22[?&]%22%20+%20name%20+%20%22(=([^&
400 (Bad Request)
just try this :
var url = window.location.hash.split('?Token=')[1];
var guid = url || '';

Calling a c# function from code behind using javascript

I need to call a c# function in my code behind using a javascript where i set two variables that i need to call my function with these variables, following my codes:
C# code behind:
public string CallWebMethod(string url, Dictionary<string, string> dicParameters)
{
try
{
byte[] requestData = this.CreateHttpRequestData(dicParameters);
HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.KeepAlive = false;
httpRequest.ContentType = "application/json; charset=utf-8";
httpRequest.ContentLength = requestData.Length;
httpRequest.Timeout = 30000;
HttpWebResponse httpResponse = null;
String response = String.Empty;
httpRequest.GetRequestStream().Write(requestData, 0, requestData.Length);
httpResponse = (HttpWebResponse)httpRequest.GetResponse();
Stream baseStream = httpResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(baseStream);
response = responseStreamReader.ReadToEnd();
responseStreamReader.Close();
return response;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
private byte[] CreateHttpRequestData(Dictionary<string, string> dic)
{
StringBuilder sbParameters = new StringBuilder();
foreach (string param in dic.Keys)
{
sbParameters.Append(param);//key => parameter name
sbParameters.Append('=');
sbParameters.Append(dic[param]);//key value
sbParameters.Append('&');
}
sbParameters.Remove(sbParameters.Length - 1, 1);
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(sbParameters.ToString());
}
and this is my javascript :
<script>
function SendNeedHelpLinkTrace() {
var keysToSend = ['pCatchLinkVirement', 'pCatchLinkCarteBancaire', 'pCatchLinkRechargePaiementFactureTelecom', 'pCatchLinkPaiementVignetteImpotTaxe', 'pCatchLinkPaiementFactureEauElectricite', 'pCatchLinkServiceFatourati', 'pCatchLinkCihExpress', 'pCatchLinkEdocuments']
var lChannelId = document.getElementById('<%= HiddenChannelId.ClientID%>').value;
var lServiceId = "900149";
var lClientId = document.getElementById('<%= HiddenClientId.ClientID%>').value;
//alert(lClientId);
var lData = keysToSend.reduce(function(p,c){
var _t = sessionStorage.getItem(c);
return isEmpty(_t) ? p : p + ' | ' + _t;
}, '')
function isEmpty(val){
return val === undefined || val === null;
}
var lCollect;
console.log(lClientId);
console.log(lData);
alert(lData);
// this is the dictionnary:
lDataCollected = lClientId + ";" + lChannelId + ";" + lServiceId + ";" + lData;
console.log(lDataCollected);
//this is the url:
var url="http://10.5.230.21:4156/CatchEvent.asmx/CollectData";
sessionStorage.clear();
}
How should i proceed ?

"Cannot read property 'match' of null"

I have that script:
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var dynamicContent = getParameterByName('utm_term');
$(document).ready(function() {
if (dynamicContent.match(/buy/i)) {
$('#buy').show();
}
else {
$('#default-content').show();
}
});
When in url there is any parametr it's working fine and else working, #deafult-content showing.
Problem that when i have clean url without parametr #default-content don't showing because "Cannot read property 'match' of null".
Any idea how to fix this?
you are returning null for !results, which you can then not match against.
try combining your two checks and return an empty string:-
function getParameterByName(name, url) {
if (!url)
url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results || !results[2])
return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var dynamicContent = getParameterByName('utm_term');
$(document).ready(function() {
if (dynamicContent.match(/buy/i)) {
$('#buy').show();
} else {
$('#default-content').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="default-content" style="display:none;">test</p>

Getting web response when button clicked in BlackBerry

I have loaded a web page in BB as follow
//RegBrowserFieldConfig extends BrowserFieldConfig
RegBrowserFieldConfig regBrowserFieldConfig = new RegBrowserFieldConfig();
//RegBrowserFieldListener extends BrowserFieldListener
RegBrowserFieldListener regBrowserFieldListener = new RegBrowserFieldListener();
BrowserField registrationBrowserField = new BrowserField(regBrowserFieldConfig);
registrationBrowserField.addListener(regBrowserFieldListener);
add(registrationBrowserField);
registrationBrowserField.requestContent("http://myurl.com/");
That web page loads fine. There is a submit button in that web page which call onsubmit in the form element in HTML. That is calling to a JavaScript function. With in that function there are some other URL that will fire according to the requirements.
What I need is to get the response of those URL calls. How can I do that?
I tried this way..
BrowserFieldListener list = new BrowserFieldListener() {
public void documentLoaded(BrowserField browserField,
Document document) throws Exception {
String url = document.getBaseURI(); //u can get the current url here... u can use ur logic to get the url after clicking the submit button
Serverconnection(url);//from this methode u can get the response
}
};
browserField.addListener(list);
Serverconnection..
public String Serverconnection(String url) {
String line = "";
// if (DeviceInfo.isSimulator()) {
// url = url + ";deviceSide=true";
// } else {
// url = url + ";deviceSide=true";
// }
url = url + getConnectionString();
try {
HttpConnection s = (HttpConnection) Connector.open(url);
s.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
s.setRequestProperty(
"Accept",
"text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
s.setRequestProperty(HttpProtocolConstants.HEADER_ACCEPT_CHARSET,
"UTF-8");
s.setRequestMethod(HttpConnection.GET);
InputStream input = s.openInputStream();
byte[] data = new byte[10240];
int len = 0;
StringBuffer raw = new StringBuffer();
while (-1 != (len = input.read(data))) {
raw.append(new String(data, 0, len));
}
line = raw.toString();
input.close();
s.close();
} catch (Exception e) {
System.out.println("response--- excep" + line + e.getMessage());
}
return line;
}
EDIT..
private static String getConnectionString() {
String connectionString = "";
if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) {
connectionString = "?;interface=wifi";
}
else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) {
connectionString = "?;&deviceside=false";
} else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) {
String carrierUid = getCarrierBIBSUid();
if (carrierUid == null) {
connectionString = "?;deviceside=true";
} else {
connectionString = "?;deviceside=false?;connectionUID="
+ carrierUid + "?;ConnectionType=mds-public";
}
} else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) {
}
return connectionString;
}
private static String getCarrierBIBSUid() {
ServiceRecord[] records = ServiceBook.getSB().getRecords();
int currentRecord;
for (currentRecord = 0; currentRecord < records.length; currentRecord++) {
if (records[currentRecord].getCid().toLowerCase().equals("ippp")) {
if (records[currentRecord].getName().toLowerCase()
.indexOf("bibs") >= 0) {
return records[currentRecord].getUid();
}
}
}
return null;
}

Categories