Unable to match a URL in webpage using Search() - javascript

walk(document.body);
function walk (node)
{
var child, next;
switch (node.nodeType)
{
case 1: //Element
case 9: //Document
case 11: //Document fragment
child = node.firstChild;
while(child) {
next = child.nextSibling;
walk(child);
child = next;
}
break;
case 3: // text node
textAndGet(node);
break;
}
}
function textAndGet(textNode)
{
var v = textNode.nodeValue;
var apiBuilder = "https://unshorten.me/s/";
var response
var link = v.search(/(?:https?:\/\/)?(?:(?:0rz\.tw)|(?:1link\.in)|(?:1url\.com)|(?:2\.gp)|(?:2big\.at)|(?:2tu\.us)|(?:3\.ly)|(?:307\.to)|(?:4ms\.me)|(?:4sq\.com)|(?:4url\.cc)|(?:6url\.com)|(?:7\.ly)|(?:a\.gg)|(?:a\.nf)|(?:aa\.cx)|(?:abcurl\.net)|(?:ad\.vu)|(?:adf\.ly)|(?:adjix\.com)|(?:afx\.cc)|(?:all\.fuseurl.com)|(?:alturl\.com)|(?:amzn\.to)|(?:ar\.gy)|(?:arst\.ch)|(?:atu\.ca)|(?:azc\.cc)|(?:b23\.ru)|(?:b2l\.me)|(?:bacn\.me)|(?:bcool\.bz)|(?:binged\.it)|(?:bit\.ly)|(?:bizj\.us)|(?:bloat\.me)|(?:bravo\.ly)|(?:bsa\.ly)|(?:budurl\.com)|(?:canurl\.com)|(?:chilp\.it)|(?:chzb\.gr)|(?:cl\.lk)|(?:cl\.ly)|(?:clck\.ru)|(?:cli\.gs)|(?:cliccami\.info)|(?:clickthru\.ca)|(?:clop\.in)|(?:conta\.cc)|(?:cort\.as)|(?:cot\.ag)|(?:crks\.me)|(?:ctvr\.us)|(?:cutt\.us)|(?:dai\.ly)|(?:decenturl\.com)|(?:dfl8\.me)|(?:digbig\.com)|(?:digg\.com)|(?:disq\.us)|(?:dld\.bz)|(?:dlvr\.it)|(?:do\.my)|(?:doiop\.com)|(?:dopen\.us)|(?:easyuri\.com)|(?:easyurl\.net)|(?:eepurl\.com)|(?:eweri\.com)|(?:fa\.by)|(?:fav\.me)|(?:fb\.me)|(?:fbshare\.me)|(?:ff\.im)|(?:fff\.to)|(?:fire\.to)|(?:firsturl\.de)|(?:firsturl\.net)|(?:flic\.kr)|(?:flq\.us)|(?:fly2\.ws)|(?:fon\.gs)|(?:freak\.to)|(?:fuseurl\.com)|(?:fuzzy\.to)|(?:fwd4\.me)|(?:fwib\.net)|(?:g\.ro.lt)|(?:gizmo\.do)|(?:gl\.am)|(?:go\.9nl.com)|(?:go\.ign.com)|(?:go\.usa.gov)|(?:goo\.gl)|(?:goshrink\.com)|(?:gurl\.es)|(?:hex\.io)|(?:hiderefer\.com)|(?:hmm\.ph)|(?:href\.in)|(?:hsblinks\.com)|(?:htxt\.it)|(?:huff\.to)|(?:hulu\.com)|(?:hurl\.me)|(?:hurl\.ws)|(?:icanhaz\.com)|(?:idek\.net)|(?:ilix\.in)|(?:is\.gd)|(?:its\.my)|(?:ix\.lt)|(?:j\.mp)|(?:jijr\.com)|(?:kl\.am)|(?:klck\.me)|(?:korta\.nu)|(?:krunchd\.com)|(?:l9k\.net)|(?:lat\.ms)|(?:liip\.to)|(?:liltext\.com)|(?:linkbee\.com)|(?:linkbun\.ch)|(?:liurl\.cn)|(?:ln-s\.net)|(?:ln-s\.ru)|(?:lnk\.gd)|(?:lnk\.ms)|(?:lnkd\.in)|(?:lnkurl\.com)|(?:lru\.jp)|(?:lt\.tl)|(?:lurl\.no)|(?:macte\.ch)|(?:mash\.to)|(?:merky\.de)|(?:migre\.me)|(?:miniurl\.com)|(?:minurl\.fr)|(?:mke\.me)|(?:moby\.to)|(?:moourl\.com)|(?:mrte\.ch)|(?:myloc\.me)|(?:myurl\.in)|(?:n\.pr)|(?:nbc\.co)|(?:nblo\.gs)|(?:nn\.nf)|(?:not\.my)|(?:notlong\.com)|(?:nsfw\.in)|(?:nutshellurl\.com)|(?:nxy\.in)|(?:nyti\.ms)|(?:o-x\.fr)|(?:oc1\.us)|(?:om\.ly)|(?:omf\.gd)|(?:omoikane\.net)|(?:on\.cnn.com)|(?:on\.mktw.net)|(?:onforb\.es)|(?:orz\.se)|(?:ow\.ly)|(?:ping\.fm)|(?:pli\.gs)|(?:pnt\.me)|(?:politi\.co)|(?:post\.ly)|(?:pp\.gg)|(?:profile\.to)|(?:ptiturl\.com)|(?:pub\.vitrue.com)|(?:qlnk\.net)|(?:qte\.me)|(?:qu\.tc)|(?:qy\.fi)|(?:r\.im)|(?:rb6\.me)|(?:read\.bi)|(?:readthis\.ca)|(?:reallytinyurl\.com)|(?:redir\.ec)|(?:redirects\.ca)|(?:redirx\.com)|(?:retwt\.me)|(?:ri\.ms)|(?:rickroll\.it)|(?:riz\.gd)|(?:rt\.nu)|(?:ru\.ly)|(?:rubyurl\.com)|(?:rurl\.org)|(?:rww\.tw)|(?:s4c\.in)|(?:s7y\.us)|(?:safe\.mn)|(?:sameurl\.com)|(?:sdut\.us)|(?:shar\.es)|(?:shink\.de)|(?:shorl\.com)|(?:short\.ie)|(?:short\.to)|(?:shortlinks\.co.uk)|(?:shorturl\.com)|(?:shout\.to)|(?:show\.my)|(?:shrinkify\.com)|(?:shrinkr\.com)|(?:shrt\.fr)|(?:shrt\.st)|(?:shrten\.com)|(?:shrunkin\.com)|(?:simurl\.com)|(?:slate\.me)|(?:smallr\.com)|(?:smsh\.me)|(?:smurl\.name)|(?:sn\.im)|(?:snipr\.com)|(?:snipurl\.com)|(?:snurl\.com)|(?:sp2\.ro)|(?:spedr\.com)|(?:srnk\.net)|(?:srs\.li)|(?:starturl\.com)|(?:su\.pr)|(?:surl\.co.uk)|(?:surl\.hu)|(?:t\.cn)|(?:t\.co)|(?:t\.lh.com)|(?:ta\.gd)|(?:tbd\.ly)|(?:tcrn\.ch)|(?:tgr\.me)|(?:tgr\.ph)|(?:tighturl\.com)|(?:tiniuri\.com)|(?:tiny\.cc)|(?:tiny\.ly)|(?:tiny\.pl)|(?:tinylink\.in)|(?:tinyuri\.ca)|(?:tinyurl\.com)|(?:tl\.gd)|(?:tmi\.me)|(?:tnij\.org)|(?:tnw\.to)|(?:tny\.com)|(?:to\.ly)|(?:togoto\.us)|(?:totc\.us)|(?:toysr\.us)|(?:tpm\.ly)|(?:tr\.im)|(?:tra\.kz)|(?:trunc\.it)|(?:twhub\.com)|(?:twirl\.at)|(?:twitclicks\.com)|(?:twitterurl\.net)|(?:twitterurl\.org)|(?:twiturl\.de)|(?:twurl\.cc)|(?:twurl\.nl)|(?:u\.mavrev.com)|(?:u\.nu)|(?:u76\.org)|(?:ub0\.cc)|(?:ulu\.lu)|(?:updating\.me)|(?:ur1\.ca)|(?:url\.az)|(?:url\.co.uk)|(?:url\.ie)|(?:url360\.me)|(?:url4\.eu)|(?:urlborg\.com)|(?:urlbrief\.com)|(?:urlcover\.com)|(?:urlcut\.com)|(?:urlenco\.de)|(?:urli\.nl)|(?:urls\.im)|(?:urlshorteningservicefortwitter\.com)|(?:urlx\.ie)|(?:urlzen\.com)|(?:usat\.ly)|(?:use\.my)|(?:vb\.ly)|(?:vgn\.am)|(?:vl\.am)|(?:vm\.lc)|(?:w55\.de)|(?:wapo\.st)|(?:wapurl\.co.uk)|(?:wipi\.es)|(?:wp\.me)|(?:x\.vu)|(?:xr\.com)|(?:xrl\.in)|(?:xrl\.us)|(?:xurl\.es)|(?:xurl\.jp)|(?:y\.ahoo.it)|(?:yatuc\.com)|(?:ye\.pe)|(?:yep\.it)|(?:yfrog\.com)|(?:yhoo\.it)|(?:yiyd\.com)|(?:youtu\.be)|(?:yuarel\.com)|(?:z0p\.de)|(?:zi\.ma)|(?:zi\.mu)|(?:zipmyurl\.com)|(?:zud\.me)|(?:zurl\.ws)|(?:zz\.gd)|(?:zzang\.kr)|(?:›\.ws)|(?:✩\.ws)|(?:✿\.ws)|(?:❥\.ws)|(?:➔\.ws)|(?:➞\.ws)|(?:➡\.ws)|(?:➨\.ws)|(?:➯\.ws)|(?:➹\.ws)|(?:➽\.ws))\/[a-zA-Z0-9]*/
);
if (!link.length) {
return;
}
var URL = apiBuilder + link;
var req = new XMLHttpRequest();
req.open("GET", URL, true);
req.send();
response = req.responseText;
textNode.nodeValue = v + " (" + response + " )";
};
Correct me if I'm wrong but wouldn't v.search return the matched value? I haven't messed with Javascript very often, but I'm attempting to make a chrome extension that will take any shortened URL on a page and display an unshortened version after it.
Now my regex does match the text if I test it in a regex tester, so I'm assuming my issue is the function that I'm using to set my variable "link".
Link is always empty regardless of the webpage. If I add a debug alert it always states it is empty as well, even if there is a link the regex would match.

string.search returns the first match index of the given string.If you want to get the match result and group.You should use v.match(regex).

Related

How can I solve my problem posting number sign to make a hashtag?

I'm trying to post # sing to make some words turn to hashtags but the code doesn't work and it's via API using this code:
true == function()
{
var getMyItem = function (str)
{
if (sessionStorage.getItem(str) == null)
{
setMyItem(str, 0);
return 0;
}
return sessionStorage.getItem(str);
}
var setMyItem = function (key, value)
{
sessionStorage.setItem(key, value);
}
function bot(post)
{
const Http = new XMLHttpRequest();
var Token="xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // Token
var ID= "xxxxxx";
var url= 'https://bot.xxx/api/'+Token+'/sendMessage?text='+post+'&chat_id='+ID;
Http.open("GET", url);
Http.send();
}
// you need to change the url variable contents for your own Telegram API or those of the same SN APIs..
So when it comes to call the post like with this code:
var myDate = new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
var post_n = "%23Hi. It's: " + myDate + "\n";
var post = encodeURI(post_n);
if (getMyItem(key + "htr") != "yes")
{
bot(post);
setMyItem((key + "htr"),"yes");
}
return true;
}
}()
, it doesnt support # sign in my browsers including Chrome an Firefox and nothing is sent actually.
So if it were for Telegram, the bot would look like this (and I donno if it works or not but I'm talking about another SN):
var url= 'https://api.telegram.org/'+Token+'...
Please tell me how to send # code. By the way, "%23" doesn't work.

Can I "queue" XMLHttpRequest functions?

I need to get a list of available files (stored in a directory) and processed files (stored in a database table).
I have some JavaScript that calls a Python script and parses its (JSON) output into an object. This works nicely whether the Python is dealing with directory files or a database table.
function runGetList() {
// request external Python script (output in JSON)
var handleResponse = function(status, response) {
// save JSON-from-Python as an object
var jsonMDBList = xhr.response;
// do stuff with the object data (build select box, build table)
}
var handleStateChange = function() {
switch (xhr.readyState) {
case 0: break; // uninitialized
case 1: break; // loading
case 2: break; // loaded
case 3: break; // interactive
case 4: // completed
handleResponse(xhr.status, xhr.response);
break;
default: alert("unspecified error");
}
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", "python/GetListMDBs.py", true);
xhr.responseType = "json";
xhr.send();
}
However, I've now reached a point where I'm going to have multiple objects (e.g. one from GetListMDBs.py, one from GetTable.py) and list them in different parts of the final HTML. My initial thought was to make runGetList() into a general function that can be called with a parameter for the particular Python script I need.
function getAllLists() {
var mdbListAll = runGetList('GetListMDBs.py');
console.log("list mdbs: " + mdbListAll);
var mdbListTbl = runGetList('GetTable.py');
console.log("table mdbs: " + mdbListAll);
}
function runGetList(filename) {
// etc.
}
This is correctly executing and getting objects from the individual Python scripts. But the getAllLists() function doesn't wait for that returned object, it just keeps going and logs list mdbs: undefined.
What can I change in my approach, so the script waits for each HTTP request to finish before moving to the next one (and doing stuff with the output)? The only workaround I have thought of is a larger, more complex JSON object that has all the lists I want embedded, but I would prefer not to do that because those Python scripts are used by a few applications and I'm trying to keep it streamlined rather than replicating code all over the place.
Try using Promise
function runGetList() {
var p = new Promise(function(resolve, reject) {
// request external Python script (output in JSON)
var handleResponse = function(status, response) {
// save JSON-from-Python as an object
var jsonMDBList = xhr.response;
// do stuff with the object data (build select box, build table)
resolve(jsonMDBList)
}
var handleStateChange = function() {
switch (xhr.readyState) {
case 0:
break; // uninitialized
case 1:
break; // loading
case 2:
break; // loaded
case 3:
break; // interactive
case 4: // completed
handleResponse(xhr.status, xhr.response);
break;
default:
alert("unspecified error");
}
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", "python/GetListMDBs.py", true);
xhr.responseType = "json";
xhr.send();
});
return p
}
function getAllLists() {
var mdbListAll = runGetList('GetListMDBs.py');
var mdbListTbl;
console.log("list mdbs: " + mdbListAll);
mdbListAll.then(function(data) {
console.log("table mdbs: " + data);
mdbListTbl = runGetList('GetTable.py');
return mdbListTbl
})
}
Based off the answer from guest271314 but with better chaining of asynchronous requests:
function runGetList(filename) {
var p = new Promise(function(resolve, reject) {
// do stuff to get jsonMDBList
resolve(jsonMDBList)
}};
return p;
}
function getAllLists() {
var mdbListAll = runGetList('GetListMDBs.py'); // returns promise 1
mdbListAll.then(function(data) { // runs when promise 1 resolves
console.log("list mdbs: " + data);
mdbListTbl = runGetList('GetTable.py'); // returns promise 2
return mdbListTbl
}).then(function(data) { // runs when promise 2 resolves
console.log("table mdbs: " + data);
});
}

bookmarklet to add a parameter to the url and resubmit it?

Is the following possible with a bookmarklet?
Add an additional parameter to the URL (include_docs=true)
Re-submit the URL
I have this but it fails silently on firefox. I haven't tried it with another browser:
javascript:(
function()
{
key = encodeURI('include_docs'); value = encodeURI('true');
var kvp = document.location.search.substr(1).split('&');
var i=kvp.length; var x; while(i--)
{
x = kvp[i].split('=');
if (x[0]==key)
{
x[1] = value;
kvp[i] = x.join('=');
break;
}
}
if(i<0) {kvp[kvp.length] = [key,value].join('=');}
//this will reload the page, it's likely better to store this until finished
document.location.search = kvp.join('&');
}()
);
No need to over-complicate anything ;-)
document.location += '&include_docs=true';
That should do the trick. In bookmarklet form:
javascript:(function(){document.location+='&include_docs=true'}());

Send multiple parameter in ajax request using javascript

So I want to use ajax request and I know how to use it.
But problem that i had that I want to pass parameters to request. So My first page had 4 parameter then I build url like this,
var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;
but now parameter is increasing like now I have 20 more. So now building url like this going to be messy approach. Is there a better way to do this.
Here is my function where i am building URL in javascript function.
function closeAssessment() {
var closeReason = document.getElementById("SectionClousureReason");
var closeReasonStr = closeReason.options[closeReason.selectedIndex].value;
var closeCmt=document.getElementById("SectionCloseAssessmentCmt").value;
var url = "./ControllerServlet?PAGE_ID=BPCLA&ACTION=closeAssessment&SAVE_FLAG=true&closeReason="+closeReasonStr+"&closeCmt="+closeCmt;
ajaxRequest(url);
return;
}
edit:
As you ask here is my ajaxRequest function,
function ajaxRequest(url) {
strURL = url;
var xmlHttpRequest = false;
var self = this;
// Mozilla, Safari
if (window.XMLHttpRequest) {
self.xmlHttpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
self.xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpRequest.open("POST", strURL, true);
self.xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
self.xmlHttpRequest.onreadystatechange = function() {
if (self.xmlHttpRequest.readyState == 4) {
if (self.xmlHttpRequest.status == 200) {
var htmlString = self.xmlHttpRequest.responseText;
var parser = new DOMParser();
var responseDoc = parser.parseFromString(htmlString, "text/html");
window.close();
} else {
ajaxFailedCount++;
// Try for 1 min (temp fix for racing condition)
if (ajaxFailedCount < 1200) {window.setTimeout(function() {ajaxRequest(url)}, 50);}
else {alert("Refresh failed!")};
}
}
}
self.xmlHttpRequest.send(null);
}
You could make an object with the key/value pairs being what you want added to the URL.
var closeReason = document.getElementById("SectionClousureReason");
var params = {
PAGE_ID: 'BPCLA',
ACTION: 'closeAssessment',
SAVE_FLAG: 'true',
closeReasonStr: closeReason.options[closeReason.selectedIndex].value,
closeCmt: document.getElementById("SectionCloseAssessmentCmt").value
};
Then add them to the URL via a loop.
var url = "./ControllerServlet?";
var urlParams = Object.keys(params).map(function(key){
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
url += urlParams;
ajaxRequest(url);
Note: I added encodeURIComponent just to be safe.
EDIT: From your comment, it seems you want to submit a <form> but you want to use AJAX to do so. In that case, you can loop over the form elements and build the above params object.
var params = {
PAGE_ID: 'BPCLA',
ACTION: 'closeAssessment',
SAVE_FLAG: 'true'
};
var form = document.getElementById('yourForm'),
elem = form.elements;
for(var i = 0, len = elem.length; i < len; i++){
var x = elem[i];
params[x.name] = x.value;
}
Build up an object of your parameters and put them in the uri through a loop like this:
var values= {
page_id: 'BPCLA',
action: 'test'
},
uri_params = [],
uri = 'http://yoururl.com/file.php?';
for (var param in values) uri_params.push( encodeURIComponent( param ) + '=' + encodeURIComponent( values[ param ] ) );
uri = uri + uri_params.join( '&' );
console.log( uri );
Or consider using POST to transport your parameters, as many browsers have limitations on the query string.
Edit: you can also build yourself a function which traverses your form and builds up the values object for you so you don't have to do it manually.
Be aware however that anyone can inject custom url paramters simpy by appending form elements before submitting the form (by using the developer tools for example) so keep that in mind.
If you are using jQuery you can use .serializeArray() or have a look at this answer for a possible function you could use.

javascript/ajax help needed

How can I get the document object out of this?
var xmlobject = (new DOMParser()).parseFromString(xmlstring, "text/xml");
In your example, xmlobject is the document object, according to MDC. According to w3schools, on IE, you need to use an IE-specific ActiveX object instead of DOMParser:
var xmlDoc, parser;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
}
else { // Internet Explorer
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(text);
}
You've said that getElementById isn't working. Note that id is not a special attribute (an attribute of type "ID") in XML by default, so even if you're giving elements an id attribute, getElementById won't work (it should return null). Details in the W3C docs for getElementById. I've never done it, but I assume you'd assign an attribute the "ID" type via a DTD.
Without one, though, you can use other traversal mechanisms. For example (live copy):
var xmlDoc, parser, text, things, index, thing;
text =
'<test>' +
'<thing>Thing 1</thing>' +
'<thing>Thing 2</thing>' +
'</test>';
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
}
else { // Internet Explorer
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(text);
}
things = xmlDoc.documentElement.getElementsByTagName('thing');
for (index = 0; index < things.length; ++index) {
thing = things.item(index);
display(index + ": " + getText(thing));
}
...where getText is:
function getText(element) {
return textCollector(element, []).join("");
}
function textCollector(element, collector) {
for (node = element.firstChild; node; node = node.nextSibling) {
switch (node.nodeType) {
case 3: // text
case 4: // cdata
collector.push(node.nodeValue);
break;
case 8: // comment
break;
case 1: // element
if (node.tagName == 'SCRIPT') {
break;
}
// FALL THROUGH TO DEFAULT
default:
// Descend
textCollector(node, collector);
break;
}
}
return collector;
}
(getText is a good example of why I use libraries like jQuery, Closure, Prototype, YUI, or any of several others for this stuff. You'd think it would be simple to get the text inside an element, and it is if the element has exactly one text node inside it [as our things do above]. If it doesn't, well, it gets complicated fast.)

Categories

Resources