I want to count users that use my bookmark in my Piwik/Matomo instance.
This is my code:
x = new Image();
x.src = 'https://piwik.jcubic.pl/matomo.php?idsite=7&rec=1&action_name=bookmark&urlref=' + location.href;
The problem is that when I open the statistic for today I don't see website with bookmark or reference on which the script was executed. I did this in incognito mode, so there was not cookie that disabled tracking for my browser.
The bookmark is REPL for Scheme language, so it's more likely be website that have Scheme learning resource or YouTube with video about Scheme. I think it's not the problem that I will track the url when bookmark was executed, there will be no information about the actual user so I think this is fine.
You can try to encode your href
const searchParams = new URLSearchParams({idsite: 7, rec: 1, action_name: 'bookmark', urlref: location.href});
const url = new URL('https://piwik.jcubic.pl/matomo.php')
url.search = searchParams.toString()
x.src = url.href;
Then you will have a URL like this with encoded special chars:
"https://piwik.jcubic.pl/matomo.php?urlref=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F63977752%2Fhow-to-track-bookmarklet-usage-using-image-in-matomo"
Related
Based on the URL I need to show either <img> or <video>. Is there a way to detect the media type based on the URL? Or maybe there is some generic html tag that allows to view both image and video? And there is no specific file extension at the end of the URL.
A simple solution in which you extract the extension from the URL and search a Map() to match element type to extension:
const types = new Map([["jpg", "img"], ["gif", "img"], ["mp4", "video"], ["3gp", "video"]])
const url = new URL("http://example.com/image.jpg")
const extension = url.pathname.split(".")[1]
const element = document.createElement(types.get(extension))
element.src = url
Original answer
Make two lists of file extensions that map to img and video files. Store these as two arrays.
When you encounter the URL - user input, JSON from REST, whatever - find the extension in the URL and see which list it belongs to.
Then create your element and inject the URL into its source, such as:
const images = ["jpg", "gif", "png"]
const videos = ["mp4", "3gp", "ogg"]
const url = new URL("http://example.com/image.jpg")
const extension = url.pathname.split(".")[1]
if (images.includes(extension)) {
let img = document.createElement('img');
img.src = url;
} else if (videos.includes(extension)) {
let video = document.createElement('video');
video.src = url;
}
This is not an especially robust solution: perhaps your paths have dots in them, but at least the use of URL() will extract the file portion of a URL that might have parameters.
Note that createElement takes any DOM node as a parent, it doesn't have to be document.
If the URL is pointing to a native file on a remote server, such as a JPG, PNG, or other image (Same for video) than you can to a Split on the last period and grab the extension.
Then once the extension is known, you can perform logic to determine if it's an image extension, or a video extension.
Otherwise, you would just initiate a programmatic download of the file and then perform the same check.
I'm using this code to download a file on click:
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(this.data, null, "\t"));
var dlAnchorElem = document.createElement('a');
dlAnchorElem.setAttribute("href", dataStr);
dlAnchorElem.setAttribute("download", "data.json");
document.body.appendChild(dlAnchorElem);
dlAnchorElem.click();
Due to some restrictions on the browsers I'm working with (inApp for android), this code does not work. So I'm thinking of a workaround..
I could use this code:
var url = "download.html";
var windowref = window.open(url, '_blank', 'location=no,closebuttoncaption=Cerrar,toolbar=yes,enableViewportScale=yes');
But since my content is dynamically generated (a dump of a json object), I can't pass it to download.html. Is there a way where window.open would take an encoded value in the URL parameter, so that when the new window opens, it would instantly download the file?
I'm trying to save downloaded file from secure url (https) with browser but I'm having problems with Firefox.
I use indexedDB to store file in browser memory and when download is finished, I try to save the file in my computer (I'm using a Mac but I think it's not important)
I have this piece of code:
var fileRequest = fileHandle.getFile(); //from indexedDB
fileRequest.onsuccess = function(event){
{...}
var file = event.target.result;
var url = window.URL.createObjectURL(file, {type : fileMimeType, autoRevoke : true});
//I did this with form and not with a href because:
//https://bugzilla.mozilla.org/show_bug.cgi?id=979227
var form = document.createElement('form');
form.action = url;
document.body.appendChild(form);
form.submit();
The browser asks to save this file in Downloads folder and everything seems to work fine BUT it prompts always this message:
"The information entered on this page will be sent through a not secure connection and could be read by third parties. Are you sure you want to send this information?"
If you click 'OK' the file is saved fine, but this security warning is the worst think a user wants to read in a webpage, so the user scares and runaway.
The created url by createObjectURL is a secure url too because is like:
blob:https//blahblah
This warning doesn't appear in Chrome (using his own filesystem method).
Please I need help :(
I use this code for avoid security warning in Firefox
var blobURL = URL.createObjectURL(some_blob);
var fr = document.createElement('iframe');
fr.frameBorder = 0;
fr.width = 1;
fr.height = 1;
document.body.appendChild(fr);
var doc = fr.contentDocument;
var form = doc.createElement('form');
form.action = blobURL;
doc.body.appendChild(form);
form.submit();
setTimeout(function(){
fr.parentNode.removeChild(fr);
}, 100);
I am developing an extension which needs to take the HTML of an external website and looks for all the downloadable links. The code I have written works... but only sometimes, because during the parse process, a lot of the websites makes the parser throw a parseError at some point. There are some webs (which are designed good enough to be able to be parsed without problems) where all the extension works perfectly. In some other websites, the parseerror makes the getElementsByTagName useless.
I guess one option would be to instead of using a DOMobject to find all the links by reading the strings... but that's way more complicated. The point is that using the Downloader extension sample from the chrome extensions dev website, it works perfectly (because instead of using the DOMobject from an external website, it creates the DOMobject from the current active tab).
I thought also of the alternative of opening a new tab with the website temporarily, loading the DOMobject from that tab and then close it and keep going on with the code, but it is a very ugly solution (the user would see a tab opening and closing...).
Edited with current code. Now I receive a document object as response, but when I want to put it in an object to deal with it the result is undefined.
//Get the HTML of the website
var xhr = new XMLHttpRequest();
xhr.open("GET",website.get_URL);
xhr.responseType = "document";
xhr.send();
doc = xhr.responseXML;
// if(xhr.responseXML !== null){
// doc = xhr.responseXML;
// } else {
// // var parser = new DOMParser();
// // doc = parser.parseFromString(xhr.response, "text/xml");
// };
console.log(xhr);
console.log(doc);
// Get all the links in the website and put them in an array (from Download extension from Chrome Extensions Samples)
var links = [].slice.apply(doc.getElementsByTagName("a"));
console.log(links);
links = links.map(function(element){
var href = element.href;
var hashIndex = href.indexOf('#');
if (hashIndex >= 0) {
href = href.substr(0, hashIndex);
}
return href;
});
I need a javascript bookmark to take the url I have in the clipboard parse out the 2 numbers and create a new url, and add a link to the top of the page, that when clicked adds the url to my bookmark menu.
Say I have url's like these
http://www.website.com/frontpageeditor.jhtml?sectionID=2844&poolID=6276
javascript:getPoolPageUrl(9800,22713)
Then I need to add the numbers to this url
javascript:frames['content'].getPoolPageUrl(9800,22713)
and then add the url to the top of the frame "content".
I have tried forever on this, but I can't figure out it out.
Update
I've put something together, to show you what I need. This one doesn't work though. Any ideas why?
var url = window.clipboardData.getData('Text');
var reg = /(\d+)/g;
var matches = url.match(reg); //returns ["2844","6276"]
var newUrl = "javascript:frames['content'].getPoolPageUrl("+matches[0]+","+matches[1]+")";
var link = document.createElement('a');
link.src = newUrl;
frames['content'].document.body.appendChild(link);
Update2
This works. Any changes I can do to make it even better?
var url = window.clipboardData.getData('text');
var matches = url.match(/(\d+)/g);
var link = frames['content'].document.createElement('a');
link.href = "javascript:frames['content'].getPoolPageUrl("+matches[0]+","+matches[1]+")";
link.innerHTML = document.title;
frames['content'].document.body.appendChild(link);
Ok, first of all I think you cannot retrieve the text from clipboard from java script, my guess that it would be a major security issue if you can.
Let's assume you have the clipboard in a string you can call this function:
var url = "http://www.website.com/frontpageeditor.jhtml?sectionID=2844&poolID=6276"; //clip
var reg = /(\d+)/g;
var matches = url.match(reg); //returns ["2844","6276"]
var newUrl = "javascript:frames['content'].getPoolPageUrl("+matches[0]+","+matches[1]+")";
frames['content'].document.getElementById("linkPlaceHolderWhereYouWantToAdd").href=newUrl;
You're creating the element in one document, and then appending it to a child located in another document. This doesn't work. You need to create the element in the document that you're going to be adding it to.
Also, the a object doesn't have a src member, it uses href.
Eg:
var link = frames['content'].document.createElement('a');
link.href = newUrl;
link.innerHTML = newUrl;
frames['content'].document.body.appendChild(link);
Do note however, that window.clipboardData is IE-specific code.
JavaScript is not permitted to access the clipboard's contents for one reason alone: Security.
If you accidentally copied your credit card number or some other personally-identifying information into your clipboard, and you visited a malicious website, it could easily snatch up your clipboard and send it off to the server before you even knew there was a risk. So, browser developers explicitly forbid it.