I am trying to set up an A/B test where the cookie will appear to 50% of the users. I have the option to place the cookie JavaScript in a field called "Head Include" of the targeted page's HTML's head, but the cookie is not appearing. The following is my script:
document.cookie = 'cname=true; Secure';
The cookie works when I place the script code in the HTML's head on the domain's site level. I have place a setting for the cookies to appear at a specific path. See following
document.cookie = 'cname=true; Secure; path=/test';
But I don't want to use the above script because I want to apply the cookie to a targeted page that will only show for 50% of targeted users and not to the site with a designated path assigned because then the cookie will show 100% of the time for that page, thus defeating the purpose of a A/B test.
My question is can a cookie be set on a specific page's HTML head and not the domain's HTML head? (Please note that names have be generalized in the code for privacy reasons)
I am still not sure if I got the problem.
You are using some kind of CMS and this CMS has the option to include scripts on a specific page ("Head include" on the target page) or an all pages ("HTML head" on domain site level). The first does not work, the latter does, but you dont want your cookie script executed on all pages.
Without seeing the generated HTML code of the (not working) target page we can't find out why its not working. If you can post a link to a prepared page (a page where the script is included and the cookie is not created) that could help to solve the problem.
Another option, without knowing the acutal problem would be shipping the script to all pages but filter the actual execution to a specific file path or url parameter. Example:
// let current = new URL(location.href); // use this to get the current url of the browser
let current = new URL('https://www.someurl.net/some_directory/some_file.ext?a=yes&b=12345'); // just an example url
if (current.searchParams.has('a') && current.searchParams.get('a') === 'yes') {
// put your cookie script here, it will be executed only if the url has an a parameter and if that parameter has the value 'yes'
}
Have a look at MDN for an overview of the properties provided by the URL class
Related
I have the following situation:
a static site, only html pages
a cookie notice system, with my own cookies, accept and refuse system of cookies setup
Now I need to inject the GA4 script into the head of pages when cookies are accepted, but...
I have already made made that, by appending the script to the head and it is visible on browser, on page reload with inspect elements...and it's working perfect.
When users click on accept cookies, the cookies accept is saved on client's side, and the script is APPENDED to page.
But I need the GA4 script to be somehow INJECTED, to be visible on the source page. Like when I preview the source page in browser to have it there. I don't need it to be injected into the html file itself, but only into the browser.
I did my own research about these days, and now it's killing me, as all I could find was the append way, but that is not injecting it into the source page on browser.
Any advice or guidance would be greatly appreciated.
Note (as I have been asking all the time. I don't want to offend anyone, but that's the best way I can explain where I want to do and what):
the source page I'm talking about is when right click on browser and view source page (there is where I need the GA4 code to be inserted)
and the way I got it to work is when right click > inspect > elements tab - (there i have it now working)
Thank you!
First question would be, why do you want it to be in the actual source code? A common way of inserting these scripts is through a tag-management-solution, which basically follows similar logic as appending scripts to the page (i.e. similar to what you meant by the inspect elements route).
To answer your question;
There is an option to get it into the sourcecode, and that is by checking on the server delivering the HTML whether a user has accepted the cookies, if that is the case deliver the HTML file (or adjust the HTML) to contain the GA4 script, if the user didn't accept: deliver the page without the GA4 script.
Since you mention these are static HTML files, I assume there is no server in place where this kind of logic can be inserted. So the best option is to insert the script afterwards.
Another way would be to insert the tag by default, but disable tracking (haven't tested the below part, also, verify yourself whether in your situation this actually blocks tracking when cookies aren't accepted):
window['ga-disable-GA_MEASUREMENT_ID'] = true;
https://developers.google.com/analytics/devguides/collection/gtagjs/user-opt-out
You could try to add this in your HTML before loading the GA4 tag, similar to something like:
<script>
const gaMeasurementId = 'G-12345678'; //replace with your own MeasurementID
let cookiesDeclined = true; //default to declined cookies
document.cookie.split(';').forEach( (cookie) =>{ //loop through all cookies
const cookie_arr = cookie.split('='); //get key/value pairs for cookies
let name = cookie_arr[0]; //cookiename
let val = cookie_arr[1]; //cookieval
if(name === 'cookieConsent' && val === 'accepted' ){
cookiesDeclined = false; //set the declined status to false when user has accepted the cookies
}
})
window['ga-disable-'+gaMeasurementId] = cookiesDeclined;
//->insert ga4 tag here
</script>
Hi I am using OneTrust for my Cookie Consent.
OneTrust gives you the option to block cookies before they are set by adding this code.
<script type="text/plain" class="optanon-category-C0002">
// code
</script>
How it works:
When the above code loads, JavaScript inside the tags will not run, and no cookies will be set. Then, when the Cookie Compliance code loads, if cookies for the associated group have consent, it will dynamically change the tag to: script type=text/JavaScript
My Problem:
How do i find the code where the cookies are being set? (Find the file).
If i know where the cookies are set, I can add the code to block it. But i dont seem to find them.
How do you search for them?
I can see in chrome all the cookie names but not sure where they are within the website.
The website has a CMS (DNN, Evoq).
Thanks in advance
I want to redirect my browser to another website and then click on a action button on that website. I think i should add some time delay in between these two tasks. The code i have written do only one event at a time.
window.location.href = "http://www.google.com";
var delayInMilliseconds = 2000;
setTimeout(function() {
document.getElementById('action-button').dispatchEvent(new MouseEvent("click"));
}, delayInMilliseconds);
It's forbidden to do this for security reasons.
In computing, the same-origin policy is an important concept in the
web application security model. Under the policy, a web browser
permits scripts contained in a first web page to access data in a
second web page, but only if both web pages have the same origin. An
origin is defined as a combination of URI scheme, host name, and port
number. This policy prevents a malicious script on one page from
obtaining access to sensitive data on another web page through that
page's Document Object Model.
Source
It is not possible in this manner.
First you change the url of the page which will stop the rest of your JS code from executing. So your timeout will never reach the google page.
Instead implement an <iframe> with the src set to http://www.google.com. Then select the iframe and look for your element in there.
This post will explain how to select the element from an iframe.
Get element from within an iFrame
At the moment you redirect the user with window.location.href any other script won't be executed.
Sort of hack to do what you want is implant script on the second website that will trigger if the user came from a specific URL. Something like that:
var URL = "OLDWEBSITEURL";
var x = window.history.back();
if (x === URL) {
document.getElementById('action-button').dispatchEvent(new MouseEvent("click"));
/* or any other code */
}
Note that if the user open the link on different window/tab or/and disable js it won't work.
EDIT:
Just a quick mention as to the nature of this program. The purpose of this program is for web inventory. Drawing different links and other content into a type of hierarchy. What I'm having trouble with is pulling a list of links from a webpage within an IFrame.
I get the feeling this one is gonna bite me hard. (other posts indicate relevance to xss and domain controls)
I'm just trying something with javascript and Iframes. Basically I have a panel with an IFrame inside that goes to whatever website you want it to. I'm trying to generate a list of links from the webpage within the Iframe. Its strictly read only.
Yet I keep coming up against the permission denied problem.
I understand this is there to stop cross site scripting attacks and the resolution seems to be to set the document domain to the host site.
JavaScript permission denied. How to allow cross domain scripting between trusted domains?
However I dont think this will work if I'm trying to go from site to site.
Heres the code I have so far, pretty simple:
function getFrameLinks()
{
/* You can all ignore this. This is here because there is a frame within a frame. It should have no effect ont he program. Just start reading from 'contentFrameElement'*/
//ignore this
var functionFrameElem = document.getElementById("function-IFrame");
console.log("element by id parent frame ");
console.log(functionFrameElem);
var functionFrameData = functionFrameElem.contentDocument;
console.log("Element data");
console.log(functionFrameData);
//get the content and turn it into a doc
var contentFrameElem = functionFrameData.getElementById("content-Frame")
console.log(contentFrameElem);
var contentFrameData = contentFrameElem.contentDocument;
console.log(contentFrameData);
//get the links
//var contentFrameLinks = contentFrameData.links;
var contentFrameLinks = contentFrameData.getElementsByTagName('a');
Goal: OK so due to this being illegal and very similar to XSS. Perhaps someone could point out a solution as to how to locally store the document. I dont seem to have any problems accessing document.links with internal pages in the frame.
Possibly some sort of temp database of cache. The simpler the solution the better.
If you want to read it just for your self and in your browser, you can write a simple proxy with php in your server. the most simple code:
<?php /* proxy.php */ readfile($_GET['url']); ?>
now set your iframe src to your proxy file:
<iframe src="http://localhost/proxy.php?url=http://www.google.com"
id="function-IFrame"></iframe>
now you can access the iframe content from your (local) server.
if you want set the url with a program remember to encode the url (urlencode in php or encodeURIComponent in js)
Here is a bookmarklet you can run on any page (assuming the links are not in an iframe)
javascript:var x=function(){var lnks=document.links,list=[];for (var i=0,n=lnks.length;i<n;i++) {var href = lnks[i].href; list.push(href)};if (list.length>0) { var w=window.open('','_blank');w.document.write(list.length+' links found<br/><ul><li>'+list.sort().join('</li><li>')+'</ul>');w.document.close()}};void(x());
the other way is for you (on Windows) to save your HTML with extension .HTA
Then you can grab whatever lives in the iFrame
You might be interested in using the YQL (Yahoo Query Language) to retrieve filtered results from remote urls..
example of retrieving all the links from the yahoo.com domain
I've read several of the questions on this but am still a little confused.
For example: OK, I can't post examples because of hyperlink limitations
Here is my exact situation.
I have a site at mydomain.com
One of the pages has an iframe to another page at sub.mydomain.com
I am trying to prepare an onload script that if the page is not in an iframe or the parent domain of the page containing the iframe is not mydomain.com then redirect to mydomain.com.
After the initial permission issues I realised the problem with sub domains counting as separate domains.
One of the posts above says that "could each use either foo.mydomain.com or just mydomain.com"
So I tried (for testing):
onload="document.domain='mydomain.com';alert(parent.location.href);"
This produced the error (http replaced with lar
Error: Permission denied for <http://sub.mydomain.net> (document.domain=<http://mydomain.net>) to get property Location.href from <http://mydomain.net> (document.domain has not been set).
Source File: http://sub.mydomain.net/?pageID=1&framed=1
Line: 1
Removing the alert produces no errors.
Maybe I am going about this the wrong way since I do not need to interact with the parent just read its domain if there is one.
A nice simple top.domain. For read only there must be a way so that people can prevent their own pages being used within other people's sites.
You can't (easily) do this because of security restrictions.
This answer from #2771397 might point you in the right direction.
OK, while looking at the error console I still had open when I got home a wee lightbulb lit up. I am pretty new to javascript (can you tell ;) but I thought "If it has try/catch"...
well here is a hack at least to get the name of the top domain and an example of how I will use it in my site to show content only if the page is a frame in the correct domain.
Firstly the header will have the following partially PHP generated function:
function getParentDomain()
{
try
{
var wibble=top.location.href;
}
catch(err)
{
if (err.message.indexOf('http://mydomain.com')!=-1)
{
createCookie('IAmAWomble','value')
}
}
}
Basically the value will be something based on the PHP session I think. This will be executed at page load.
If the page is not within the proper site or if javascript is not enabled then the cookie will not be created.
PHP will then attempt to read the correct value from the cookie and show the content or an error message as appropriate.
I do see a slight flaw in this for first visit since page load will run after PHP has generated the content but I'm sure I can work around this somehow. I thought I'd post because this is at least what I was initially asking for and that is a way to read the URL of a parent site if it is in a different domain to the site in the frame.
IIUC you want to use the window.parent attribute: “A reference to the parent of the current window or subframe.”
Assumably, window.parent.document.location.host contains the container page URL domain name.