Javascript -Trim Array of URL's to Root Domain - javascript

I am developing a chrome extension that can copy the urls of all tabs in a browser. The problem is i can only trim one url in all the array. Is there a way i can output all the root domain in the popup?thanks in advance
example of the tabs url
youtube.com/asdwea/asdsa
google.com/asdwew
facebook.com/qwea/asd
the result for the popup should be
youtube.com
google.com
facebook.com
popup.html
<html>
<script src="popup.js"></script>
<body>
<div id="result"></div>
<div id="count"> all</div>
</body>
</html>
popup.js
chrome.windows.getAll({populate:true}, getAllOpenWindows);
function getAllOpenWindows(winData) {
var tabs = [];
for (var i in winData) {
if (winData[i].focused === true) {
var winTabs = winData[i].tabs;
var totTabs = winTabs.length;
for (var j=0; j<totTabs;j++) {
tabs.push(winTabs[j].url+ "</br>");
}
var domain = tabs[1].replace('http://','').replace('https://','').split(/[/?#]/)[0];
}
}
document.getElementById('count').innerHTML = tabs.length;
document.getElementById('result').innerHTML = domain;
}

function getAllOpenWindows(winData) {
var tabs = [];
for (var i in winData) {
if (winData[i].focused === true) {
var domainStr = "";
var winTabs = winData[i].tabs;
var totTabs = winTabs.length;
for (var j=0; j<totTabs;j++) {
var str = winTabs[j].url+ "</br>";
tabs.push(str);
domainStr += str;
}
domainStr = domainStr.replace('http://','').replace('https://','').split(/[/?#]/)[0];
}
}
document.getElementById('count').innerHTML = tabs.length;
document.getElementById('result').innerHTML = domainStr;
}
I think what you need is concat all strings, which is domainStr here.
As your question is not related to split function, I did not check whether .replace('http://','').replace('https://','').split(/[/?#]/)[0]; works.

Related

Adding Elements to Weebly via Javascript Not Working

I have some Javascript code that reads a published Google Sheet and reads it to the webpage. For some reason upon embedding this int Weebly, it just doesn't want to take it. No elements are created at all as far as i can tell. Here is my code, any help is awesome.
<!DOCTYPE html><!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var spData = null;
function doData(json) {
spData = json.feed.entry;
}
function readData(parent) {
var data = spData;
var ScoreObjs = [];
var ScoreObj = new Object();
for(var r=4; r < data.length; r++) {
var cell = data[r]["gs$cell"];
var val = cell["$t"];
console.log(val);
if (cell.col == 1) {
ScoreObj.team1 = val;
}
else if (cell.col == 2) {
ScoreObj.team2 = val;
}
else if (cell.col == 3) {
ScoreObj.score1 = val;
}
else if (cell.col == 4) {
ScoreObj.score2 = val;
ScoreObjs.push(ScoreObj);
ScoreObj = new Object();
}
}
toFormat(ScoreObjs);
}
function toFormat(obj) {
for (var x = 0; x < obj.length; x++)
{
var data = obj[x];
var team1 = data.team1;
var team2 = data.team2;
var score1 = data.score1.toString();
var score2 = data.score2.toString();
var child1 = document.createElement("div");
child1.className = "paragraph";
document.body.appendChild(child1);
var child2 = document.createElement("strong");
child1.appendChild(child2);
var child3 = document.createElement("font");
child3.color = "#FFFFFF";
child3.innerHTML = team1 + " vs " + team2 + "<br />ESEA Scrim";
child2.appendChild(child3);
var child4 = document.createElement("font");
child4.color = "#00FF00";
child4.innerHTML = score1 + ":" + score2;
child1.appendChild(child4);
}
}
$(document).ready(function(){
readData($("#data"));
});
</script>
<script src="https://spreadsheets.google.com/feeds/cells/1BSsomIQwFhifrFB8ybQ6xF0t-KdJNKtCBHotY3X8O98/1/public/values?alt=json-in-script&callback=doData"></script>
</head>
</html>
Change:
<script
src="https://spreadsheets.google.com/feeds/cells/1BSsomIQwFhifrFB8ybQ6xF0t-KdJNKtCBHotY3X8O98/1/public/values?alt=json-in-script&callback=doData"></script>
To:
<script id="data"
src="https://spreadsheets.google.com/feeds/cells/1BSsomIQwFhifrFB8ybQ6xF0t-KdJNKtCBHotY3X8O98/1/public/values?alt=json-in-script&callback=doData"></script>
This could be because the javascript code runs first and renders some problems. I had the same problem.
Include script tags in the footer and not in the head section.
In fact you will find default Weebly script tags below the footer. Add your custom javascript code along with that.
OR
(MORE PREFERABLE)
Create a javascript(.js) file externally upload it to Assets in weebly theme editor and then add it to your HTML header file along with other default weebly script tags.
eg. a javascript file named editsite.js will be added like this (after uploading to assets):
<script type="text/javascript" src="/files/theme/editsite.js"></script>

Android WebView - innerHTML doesn't update value

I use such function to load data to WebView after loading page. Console tells what value of innerHTML is update but on WebView change don't show. In browser console everything is fine.
<script language="javascript" type="text/javascript">
function init_order() {
var elems = document.getElementById("body-id").getElementsByClassName("order_data");
if(arguments.length == elems.length){
console.log("Number of arguments is correct.");
}
else{
console.log("Incorrect number of arguments.");
console.log("Class Tag: "+elems.length);
console.log("Arguments: "+arguments.length);
}
for(i = 0; i < elems.length ; ++i){
var tag = elems[i];
var tagValue = elems[i].innerHTML;
if(tagValue.search("%#") != -1){
var replacedStr = tagValue.replace("%#",arguments[i]);
elems[i].innerHTML = replacedStr;
//console.log(arguments[i]);
console.log("value: "+elems[i].innerHTML);
}
}
// window.location.reload()
}
</script>

replacing text that has url with an anchor with regex

var a = document.querySelectorAll('.post .content div');
var b = a[7].childNodes;
for(i=0;i<b.length;i++){
var exp = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|])/ig;
if(b[i].nodeType === 3){
var ahref = document.createElement('a');
ahref.className="easyBBurlFetch";
ahref.href=b[i].nodeValue.replace(exp,'$1');
ahref.innerText=b[i].nodeValue.replace(exp,'$1');
b[i].parentNode.insertBefore(ahref,b[i]);
b[i].parentNode.removeChild(b[i].nextSibling);
}
}
Someone gave me the answer as I had this code though it wasn't working correct. Though I have the issue now if my text is like so:
This is just a test so click here www.youtube.com which then becomes
www.youtube.com%20which%20then%20becomes
It doesn't event keep the first line of text, I just need to parse the url while keeping the surrounding text.
In need the output to save the actual surrounding text but parse the urls that are inside the text to html anchor tags <a> so that they can then be clickable and actually follow through to a real website and not have unnessarcy text inside it from what my user was writing about. Thank you
UPDATE
I've got closer to making this work-- But I'm having a problem with the first text in the string is saying Undefined I've been debugging this and can't seem to figure out why this is happening. Here is code
var a = document.querySelectorAll('.post');
var b = a[0].childNodes;
var textArray;
var ahref;
for (i = 0; i < b.length; i++) {
var exp = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|])/ig;
if (b[i].nodeType === 3) {
var newHTML;
textArray = b[i].textContent.split(" ");
for (var j = 0; j < textArray.length; j++) {
if (textArray[j] !== "" && validURL(textArray[j])) {
ahref = document.createElement('a');
ahref.href = (/^(http:\/\/|https:\/\/)/).test(textArray[j]) ? textArray[j] : "http://" + textArray[j];
ahref.innerText = textArray[j];
ahref.className = "easyURLparse";
textArray[j] = ahref;
}
newHTML+= textArray[j].outerHTML ? textArray[j].outerHTML + " " : textArray[j] + " ";
}
var div = document.createElement('div');
div.innerHTML = newHTML;
newHTML = "";
b[i].parentNode.insertBefore(div, b[i]);
b[i].parentNode.removeChild(b[i].nextSibling);
}
}
function validURL(str) {
var pattern = new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+#)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?");
if (!pattern.test(str)) {
return false;
} else {
return true;
}
}
Testing Code
Just need to figure out the undefined and why it's adding it
this regexp will do the job
exp = /href="(\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|])"/ig;
var a = document.querySelectorAll('.post');
var b = a[0].childNodes;
var textArray;
var ahref;
for (i = 0; i < b.length; i++) {
var exp = /(\b(https?|ftp|file):\/\/[\-A-Z0-9+&##\/%?=~_|!:,.;]*[\-A-Z0-9+&##\/%=~_|])/ig;
if (b[i].nodeType === 3) {
var newHTML;
if (validURL(b[i].textContent)) {
textArray = b[i].textContent.split(" ");
for (var j = 0; j < textArray.length; j++) {
if (textArray[j] !== undefined && textArray[j] !== "" && validURL(textArray[j]) && textArray[j] !== null) {
ahref = document.createElement('a');
ahref.href = (/^(http:\/\/|https:\/\/)/).test(textArray[j]) ? textArray[j] : "http://" + textArray[j];
ahref.innerText = textArray[j];
ahref.className = "easyURLparse";
textArray[j] = ahref;
}
newHTML += textArray[j].outerHTML ? textArray[j].outerHTML + " " : textArray[j] + " ";
}
var div = document.createElement('div');
div.innerHTML = newHTML;
div.className = "easyDiv";
b[i].parentNode.insertBefore(div, b[i]);
b[i].parentNode.removeChild(b[i].nextSibling);
}
newHTML = "";
}
}
function validURL(str) {
var pattern = new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+#)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?(/.*)?");
if (!pattern.test(str)) {
return false;
} else {
return true;
}
}
By taking the textNodes and splitting them into an array I can then change the url into an html element. Then taking the array elements seeing if there is outerHTML or not then placing it in a new string and replacing that textNode now with a workable link.
Working example

onclick event get value from javascript function not working

I have this line
<td><xsl:value-of select="product_name"/></td>
When i try to get the return value of the function getTableRow() and display it to href link i take key=undefined.Why happen that?
This is my script on the head of html
<script type="text/javascript">
function getTableRow() {
var rowIdx;
var rowData= [];
var selectedRow;
var rowCellValue;
if (!document.getElementsByTagName || !document.createTextNode) return;
var rows = document.getElementById('products_table').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
rowIdx = this.rowIndex;
selectedRow= this.cells;
for(j= 0;j<selectedRow.length;j++){
rowCellValue= selectedRow[j].textContent ||
selectedRow[j].innerText;
rowData.push('cell '+j+': '+rowCellValue);
}
}
}
return "Row #" +rowIdx+'. '+ rowData[i];
}
</script>
I try many solution but nothing work..Please help..
In the beginning the only thing i want is to return the rowIndex.Even in that i get undefined.Why happend that?My first code before i try to get the content from row that user select.
<script type="text/javascript">
var userSelect;
function getTableRow() {
if (!document.getElementsByTagName || !document.createTextNode) return;
var rows = document.getElementById('products_table').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
userSelect = this.rowIndex;
}
}
return userSelect;
}
</script>
It's probably being caused
if (!document.getElementsByTagName || !document.createTextNode) return;
If you are getting undefined.
Best thing I can suggest is throw a load of debugging in e.g. :
<script type="text/javascript">
function getTableRow() {
console.log( "getTableRow function called" );
var rowIdx;
var rowData= [];
var selectedRow;
var rowCellValue;
if (!document.getElementsByTagName || !document.createTextNode) {
console.log( document.getElementsByTagName, document.createTextNode, "Returning early" );
return;
}
var rows = document.getElementById('products_table').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
rowIdx = this.rowIndex;
selectedRow= this.cells;
for(j= 0;j<selectedRow.length;j++){
rowCellValue= selectedRow[j].textContent ||
selectedRow[j].innerText;
rowData.push('cell '+j+': '+rowCellValue);
}
}
}
console.log( "Returning correctly" );
return "Row #" +rowIdx+'. '+ rowData[i];
}
</script>
If you're using firefox get yourself http://getfirebug.com/ and see what the console outputs
If you're using chrome press F12 and click on console and see what that says
If you're unsure about what's available in the document element try :
https://developer.mozilla.org/en/docs/Web/API/Element
http://msdn.microsoft.com/en-us/library/ie/ms535862(v=vs.85).aspx
http://www.w3schools.com/jsref/dom_obj_document.asp

Javascript in DotNetNuke 6.1.3

I am building a website in DNN, and I want to include Javascript in one of its HTML Modules.
I added the Javascript in footer/header (Settings > Advance Settings) but it didn't work. Then I tried adding the content by switching to basic editor and selecting RAW mode, but it's still not working.
Here is my Javascript. It is for tab browsing, to test whether Javascript is working or not I wrote a simple script in another HTML module, and it worked fine, but this script isn't running:
<script type="text/javascript">
var tabLinks = new Array();
var contentDivs = new Array();
function init() {
var tabListItems = document.getElementById('tabs').childNodes;
for (var i = 0; i < tabListItems.length; i++) {
if (tabListItems[i].nodeName == "LI") {
var tabLink = getFirstChildWithTagName(tabListItems[i], 'A');
var id = getHash(tabLink.getAttribute('href'));
tabLinks[id] = tabLink;
contentDivs[id] = document.getElementById(id);
}
}
var i = 0;
for (var id in tabLinks) {
tabLinks[id].onclick = showTab;
tabLinks[id].onfocus = function() {
this.blur()
};
if (i == 0) tabLinks[id].className = 'selected';
i++;
}
var i = 0;
for (var id in contentDivs) {
if (i != 0) contentDivs[id].className = 'tabContent hide';
i++;
}
}
function showTab() {
var selectedId = getHash(this.getAttribute('href'));
for (var id in contentDivs) {
if (id == selectedId) {
tabLinks[id].className = 'selected';
contentDivs[id].className = 'tabContent';
} else {
tabLinks[id].className = '';
contentDivs[id].className = 'tabContent hide';
}
}
return false;
}
function getFirstChildWithTagName(element, tagName) {
for (var i = 0; i < element.childNodes.length; i++) {
if (element.childNodes[i].nodeName == tagName) return element.childNodes[i];
}
}
function getHash(url) {
var hashPos = url.lastIndexOf('#');
return url.substring(hashPos + 1);
}​
</script>
There shouldn't be any problem with adding JavaScript to the header/footer. When you say it didn't work, did you check the source of the page, or did the behavior just not work? Did you check for JavaScript errors in your browser's console?
So far as adding JavaScript via the Basic/Raw view of the rich text editor, DNN strips JavaScript from the text editor by default. You can turn that off via the HTML Editor Manager (under Host).

Categories