How do I pass configurations to index.html in Vue - vue.js

I would like to pass google tag manager id based on the environment to my script in index.html in my vue app but I can't find a way to pass configs to a html file. Kindly assist.
Here is the script
<script>
(function (w, d, s, l, i) {
w[l] = w[l] || [];
w[l].push({ "gtm.start": new Date().getTime(), event: "gtm.js" });
var f = d.getElementsByTagName(s)[0],
j = d.createElement(s),
dl = l != "dataLayer" ? "&l=" + l : "";
j.async = true;
j.src = "https://www.googletagmanager.com/gtm.js?id=" + i + dl;
f.parentNode.insertBefore(j, f);
})(window, document, "script", "dataLayer", "<env-gtm-id-goes-here>"
</script>

You can use the html interpolation. Refer here
In combination with the vue Environment Variables. Refer Here
For example:
make a new file name .env and make entry
VUE_APP_ENVARS=prod and use it inside your index.html with the html interpolation
<p>The username to test is <%= VUE_APP_ENVIR %></p>
Update: Since you need to access this variable in the <script> tag, use this
(window, document, "script", "dataLayer", "<%= VUE_APP_ENVIR %>"

Related

Using document.getElementsByClassName in Testcafe

I have a menu that always has the same structure, but the IDs can change from one installation to another. the only thing that stays the same is the heading (in my case "Plugins"). I call the document.getElementsByClassName function with a Selector inside my test:
var slides = Selector(() =>{
return document.getElementsByClassName("c-p-header-text");
});
Every heading of an menu element has the c-p-header-text class. Here is what a menu heading element looks like:
<div id="ext-comp-1002" class="c-p c-tree c-p-collapsed" style="width: auto;">
<div class="c-p-header c-unselectable c-accordion-hd" id="ext-gen135" style="cursor: pointer;">
<div class="c-tool c-tool-toggle" id="ext-gen140"> </div>
<img src="/backEnd/images/s.gif" class="c-p-inline-icon order"><span class="c-p-header-text" id="ext-gen150">Plugins</span>
</div>
It would be easy to use await t.click("#ext-gen150") but it is not safe that it is always this id.
here is what i tried:
await t
.click('#sites__db');
var slides = Selector(() =>{
return document.getElementsByClassName("c-p-header-text");
});
console.log("[DEBUG]" + slides);
console.log("[DEBUG] found " + slides.length + " elements");
for(var i = 0; i < slides.length; i++)
{
var txtOfCurrElem = slides.item(i).innerText;
console.log("[DEBUG "+ i +"] Text: " + txtOfCurrElem);
}
Running this test give me the following output:
[DEBUG]function __$$clientFunction$$() {
var testRun = builder.getBoundTestRun() || _testRunTracker2.default.resolveContextTestRun();
var callsite = (0, _getCallsite.getCallsiteForMethod)(builder.callsiteNames.execution);
var args = [];
// OPTIMIZATION: don't leak `arguments` object.
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}return builder._executeCommand(args, testRun, callsite);
}
[DEBUG] found 0 elements
The plan is to find the element (with the heading "Plugins") and then click on it when the test continuous.
You don't have to use document.getElementsByClassName in this case. You can just use CSS class selector instead:
var slides = Selector('.c-p-header-text');
You should use the count property when dealing with an array of Selectors. docs. Also, element properties, like exists, count, and DOM node state properties are Promisified, so when you use them not in t.expect, you should use the await keyword:
var count = await slides.length;
console.log("[DEBUG] found " + count + " elements");
for(var i = 0; i < count; i++)
{
var txtOfCurrElem = await slides.nth(i).innerText;
console.log("[DEBUG "+ i +"] Text: " + txtOfCurrElem);
}
I found a simple answer to my question. I use the .withText option to click on the Plugins element:
.click(Selector('span').withText("Plugins"))
Since this name is also unique, it is always the correct element that gets clicked. I do not know if it would have worked with the solution from #AndreyBelym if my site is not an extJS web application.

IE won't download file generated with rails

I have created 2 buttons that allow a user to download a HTML table as TXT or Excel. The appropriate files are generated by my Rails app. Everything works fine except for IE. I tested IE11 on Win7.
Live example (See buttons at bottom): http://en.mycoursewalk.com/course_walk/distance_table/3575
HTML Code:
<i class="fa fa-file-excel-o fa-lg"></i> Export to Excel
<script>
var cw_id = <%= #coursewalk.id %>;
$(document).on("pageshow",function(event) {
$("#Export_Excel").click(function(event) {
export_table('xml');
});
});
function export_table(export_format) {
var table = $('#distance_table').tableToJSON();
window.open('/application/export_table/' + cw_id + '.' + export_format + '?table_type=distance_table&export_format=' + export_format + "&_json=" + encodeURIComponent(JSON.stringify(table)), "_self");
}
</script>
Controller:
def export_table
# Code here to create appropriate text or Excel file. Removed for clarity
formatted_data = ''
formatted_data << "test" + "\t" + "test2" + "\n"
i = Iconv.new('UTF-8','iso-8859-1')
formatted_data_utf8 = i.iconv(formatted_data)
send_data formatted_data_utf8, :filename => "test.txt", :type => "text/csv;charset=UTF-8", :disposition => "attachment"
end
In the IE Developer Tools and Console, IE shows "Navigation Occurred" and a complaint about DOCTYPE when you click on the Export buttons. Clicking on the DOCTYPE warning will actually load the TXT or Excel file into the console.
How can I fix this?
I fixed this issue by using rails templates instead as described in this Rail Cast:
http://railscasts.com/episodes/362-exporting-csv-and-excel?view=asciicast

SharePoint 2010 Wiki Template Script Issue

I'm looking for a way to give my SharePoint users a way to create new wiki pages from an existing template. In the process of researching I found a great walkthrough that seems to fit the need (http://www.mssharepointtips.com/tip.asp?id=1072&page=2), but I'm having trouble getting it to work. The problem seems to lie in the assignment of a path to PATHTOWIKI-- if I use "/Weekly Update Wiki", the script returns an error of "There is no Web named '/Weekly Update Wiki'." If I use "Weekly Update Wiki" without the forward slash, I instead get an error of "There is no Web named '/sites/[parentSite]/[childSite]/Weekly Update Wiki/Weekly Update Wiki'."
Any ideas about what I'm not understanding here?
function myCreateProject() {
// Configure these for your environment
// include no slashes in paths
var PATHTOWIKI = "Weekly Update Wiki";
var PATHTOPAGES = "Pages";
// file name only for template page, no extension
var TEMPLATEFILENAME = "Template";
var myPathToWiki = encodeURIComponent(PATHTOWIKI);
var myPathToPages = PATHTOPAGES + "%2f";
var myTemplateFileName = encodeURIComponent(TEMPLATEFILENAME) + "%2easpx";
var EnteredProject = document.getElementById("NewProjName");
var myNewName = EnteredProject.value;
if(myNewName == "") {
alert('Please enter a name for the new project page');
} else {
myNewName = encodeURIComponent(myNewName) + "%2easpx"
$.ajax({
url: PATHTOWIKI + "/_vti_bin/_vti_aut/author.dll",
data: ( "method=move+document%3a14%2e0%2e0%2e4730&service%5fname="
+ myPathToWiki +
"&oldUrl=" + myPathToPages + myTemplateFileName +
"&newUrl=" + myPathToPages + myNewName +
"&url%5flist=%5b%5d&rename%5foption=nochangeall&put%5foption=edit&docopy=true"
),
success: function(data) {
var rpcmsg1 = getMessage(data, "message=", "<p>");
$("#myInfo").append("<br />" + rpcmsg1);
if(rpcmsg1.indexOf("successfully") < 0) {
// get error info
var rpcmsg2 = getMessage(data, "msg=", "<li>");
$("#myInfo").append("<br />" + rpcmsg2 + "<br />");
} else {
$("#myInfo").append("<br />Go to new page<br />");
}
},
type: "POST",
beforeSend: function(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("X-Vermeer-Content-Type",
"application/x-www-form-urlencoded");
}
});
}
}
Update: I figured out what needed to happen in my case. Since I couldn't get a grasp on the relative approach, I just went with the absolute path for PATHTOWIKI and slightly modified the append in the ajax call.
PATHTOWIKI:
var PATHTOWIKI = "https://[domain]/sites/[parentSite]/[childSite]";
append:
$("#myInfo").append("<br />Go to new page<br />");
The change in the latter line of code is subtle; since I used an absolute path in PATHTOWIKI, I just removed the leading forward slash in the anchor tag, so that <a href=\"/" became <a href=\"". This renders the script slightly less portable, but since it's a one-off effort I'll stick with this unless anything comes along to expand the scope.

apache rewrite all hash tag to slash tag under one directory

How to rewrite all hash tag to slash tag under one directory? (apache)
http://www.domain.com/company/index#about => http://www.domain.com/company/index/about
http://www.domain.com/company/article#123456 => http://www.domain.com/company/article/123456
http://www.domain.com/company/events#October => http://www.domain.com/company/events/October
So, all the pages witch in /company/, rewrite # => /.
$(window).on('hashchange', function() {
//
}
In general all the browsers exclude the fragment part (#) from the request to the server. If you really want do it, you must rewrite the urls before call the server
function addHashtag2Pathname(url){
var a = document.createElement('a');
a.href = url;
if (a.pathname.substr(-1) != "/")
a.pathname = a.pathname + '/';
a.pathname += a.hash.replace(/^#/,'');
a.hash = '';
return a.href.replace(/#$/,'');
}
You can see this function in action here
http://jsfiddle.net/bknE4/43/
Actually I haven't tried this below, but it should work...
$(window).on('hashchange', function() {
var newurl = addHashtag2Pathname(location.href);
location.href = newurl;
})
If you navigate your web browser to http://www.domain.com/company/events#October, it will fetch the URL http://www.domain.com/company/events from the server. The server does not see the rest of the URL and can do nothing with it. Only Javascript can act on it.
$(window).on('hashchange', function() {
var a_tags = document.getElementsByTagName('a');
for (var i = 0; i < a_tags.length; i = i + 1) {
var elem = a_tags[i];
if (/company.*#/.test(elem.href)){
elem.href = elem.href.replace('#', '/');
}
}
}
You might want to change the regexp in the if conditional to be more specific.
The same for the replace function.
However I would change the HTML server side instead if it is supposed to be permanent.

Get the hostname with action script 2

I am creating some campaign swf banners and I don't use action script very often so any help from the experts would be great thanks.
I am supplying my banners on my website as resource downloads. And tutorials of how to embed the swf which has some javascript flashvars.
These flash variable is then concatenated into a google campaign link to change the utm_source.
This is my javascript...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript">
var flashvars = {};
flashvars.campaignSource = window.location.hostname;
var params = {};
params.loop = "true";
params.quality = "best";
params.wmode = "opaque";
params.swliveconnect = "true";
params.allowscriptaccess = "always";
var attributes = {};
swfobject.embedSWF("banner.swf", "banner_mpu", "300", "250", "9.0.0", false, flashvars, params, attributes);
</script>
and my html...
<div id="banner_mpu">
<a href="http://www.adobe.com/go/getflashplayer">
<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
</a>
</div>
So the above js works great, however, not everyone will use my tutorial code and will probably use there own methods to embed the swf banner on their site.
So I need some back up action script 2 to get the current hostname into a action script variable
This is my action script which I have so far on my button (swf)...
on(release) {
function GetTheHostname() {
var RootFullUrl = _root._url;
txtFullUrl.text = RootFullUrl;
var lastSlashIndex:Number = RootFullUrl.lastIndexOf("/");
var DriveIndex:Number = RootFullUrl.indexOf("|");
if (DriveIndex>=0) {
baseUrl = RootFullUrl.substring(0, DriveIndex);
baseUrl += ":";
} else {
baseUrl = "";
}
baseUrl += RootFullUrl.substring(DriveIndex+1, lastSlashIndex+1);
txtBaseUrl.text = baseUrl;
return baseUrl;
}
var campaignSourceAS2:String= GetTheHostname();
if ( _root.campaignSource == undefined ) {
getURL("http://www.mysite.co.uk/?utm_source=" + campaignSourceAS2 + "&utm_medium=MPU&utm_campaign=My%20Campaign%202012", "_blank");
} else {
getURL("http://www.mysite.co.uk/?utm_source=" + _root.campaignSource + "&utm_medium=MPU&utm_campaign=My%20Campaign%202012", "_blank");
}
}
The problem with my action script is that it returns the full current URL.
Can any one please help me adapt the GetTheHostname function to get the host name instead of the baseURL
Thanks in advance
In that case, I guess it would be as easy as stripping the http:// from the url and then get all that's left to the first /
A one-liner to go from 'http://www.example.com/category/actionscript' to 'www.example.com' would be
var baseURL:String = _root._url.split("http://").join("").split("/")[0];
and to replace your full method
getURL("http://www.mysite.co.uk/?utm_source=" + (_root.campaignSource || _root._url.split("http://").join("").split("/")[0]) + "&utm_medium=MPU&utm_campaign=My%20Campaign%202012", "_blank");