I'm trying to figure out how I can use these scripts in order to display a linkedin follow button. I am using Angular 4, however, and understand that scripts shouldn't really be used. I am trying to implement the code given by the linkedin developer site
<script src="//platform.linkedin.com/in.js" type="text/javascript"> lang: en_US</script>
<script type="IN/FollowCompany" data-id="218698" data-counter="right"></script>
But it doesn't display. I've tried to see if there are any other alternatives, but the best I found was ng-share, but to my understanding, that doesn't have a follow button, only a share button. I am open to alternatives, but preferably would like to have the button look the same as the one provided by the linkedin developer site.
Edit: I am using an instance in which the twitter widget script is being inserted.
import { Component, Input } from '#angular/core';
import { NavigationService } from '../../services/navigation.service';
import { ContentService } from '../../services/content.service';
import { Category } from '../../services/models/category';
import { ShareButtonsModel } from '../../services/models/body-component';
import { BrowserModule, DomSanitizer, SafeHtml } from '#angular/platform-browser';
#Component({
selector: 'share-buttons',
templateUrl: './share-buttons.component.html',
styleUrls: ['./share-buttons.component.css']
})
export class ShareButtonsComponent {
#Input('share-buttons-layout') shareButtonsLayout: ShareButtonsModel;
#Input('share-buttons-data') shareButtonsData;
externalHTML: SafeHtml;
categories: Category[];
constructor(private sanitizer: DomSanitizer, public cService: ContentService, public nService: NavigationService) {
let htmlStr = `<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
`;
this.downloadJS(htmlStr);
this.externalHTML = this.sanitizer.bypassSecurityTrustHtml(htmlStr);
}
ngOnInit() {
this.cService.getLayout().subscribe(res => this.categories = res);
}
downloadJS(string) {
var parser = new DOMParser();
var scripts = parser.parseFromString(string, 'text/html').getElementsByTagName('script');
var head = document.getElementsByTagName('head')[0];
//var result = [];
for (var i = 0; i < scripts.length; i++) {
var src = scripts[i].getAttribute('src');
var script = document.createElement('script');
if (src && src.length) {
script.src = (src);
} else {
script.innerHTML = scripts[i].innerHTML;
}
document.head.appendChild(script);
head.removeChild(script);
}
}
}
And the html where I add the twitter button is here:
<!--Twitter Follow-->
<div *ngIf="button.button==='twitterFollow'">
Follow #dummyComp
</div>
It seems to work perfectly fine when I navigate to and from my site.
(Angular 5) I am able to display a functional "LinkedIn Follow" button in a component, however it appears that the iframe is corrupted/trashed when navigation is routed to another component and back again.
index.html:
<body>
<!-- Scripts -->
<div id="linkedin-scripts" style="display:none;">
<script src="//platform.linkedin.com/in.js" type="text/javascript">lang: en_US</script>
<script type="IN/FollowCompany" data-id="" data-counter="right"></script>
</div>
<app-root></app-root>
</body>
your.component.html
<div id="linkedin"></div>
your.component.ts
ngOnInit() {
document.getElementById("linkedin").innerHTML = document.getElementById("linkedin-scripts").innerHTML;
}
You can add code in ngAfterViewInit function and add a script tag dynamically such as :-
const s = document.createElement('script');
s.type = 'in/Login';
var elementRef = document.getElementById("linkedinBtn"); // element or div
where you want to add the button
elementRef.appendChild(s);
Related
I have following code to include amplitude js for tracking using Script tag. But, amplitude is not loading events.
import Document, { Html, Head, Main, NextScript } from 'next/document';
import Script from 'next/script';
<Html lang="en">
<Head>
<Script
async
key="amplitude"
src="/js/analytics/amplitude.js"
></Script>
</Head>
</Html>
amplitude.js has following code which includes amplitude using SDK way here
(function(e,t){var n=e.amplitude||{_q:[],_iq:{}};var r=t.createElement("script")
;r.type="text/javascript"
;r.integrity="sha384-MBHPie4YFudCVszzJY9HtVPk9Gw6aDksZxfvfxib8foDhGnE9A0OriRHh3kbhG3q"
;r.crossOrigin="anonymous";r.async=true
;r.src="https://cdn.amplitude.com/libs/amplitude-8.16.1-min.gz.js"
;r.onload=function(){if(!e.amplitude.runQueuedFunctions){console.log(
"[Amplitude] Error: could not load SDK")}};var s=t.getElementsByTagName("script"
)[0];s.parentNode.insertBefore(r,s);function i(e,t){e.prototype[t]=function(){
this._q.push([t].concat(Array.prototype.slice.call(arguments,0)));return this}}
var o=function(){this._q=[];return this};var a=["add","append","clearAll",
"prepend","set","setOnce","unset","preInsert","postInsert","remove"];for(
var c=0;c<a.length;c++){i(o,a[c])}n.Identify=o;var l=function(){this._q=[]
;return this};var u=["setProductId","setQuantity","setPrice","setRevenueType",
"setEventProperties"];for(var p=0;p<u.length;p++){i(l,u[p])}n.Revenue=l;var d=[
"init","logEvent","logRevenue","setUserId","setUserProperties","setOptOut",
"setVersionName","setDomain","setDeviceId","enableTracking",
"setGlobalUserProperties","identify","clearUserProperties","setGroup",
"logRevenueV2","regenerateDeviceId","groupIdentify","onInit","onNewSessionStart"
,"logEventWithTimestamp","logEventWithGroups","setSessionId","resetSessionId",
"getDeviceId","getUserId","setMinTimeBetweenSessionsMillis",
"setEventUploadThreshold","setUseDynamicConfig","setServerZone","setServerUrl",
"sendEvents","setLibrary","setTransport"];function v(t){function e(e){
t[e]=function(){t._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}
for(var n=0;n<d.length;n++){e(d[n])}}v(n);n.getInstance=function(e){e=(
!e||e.length===0?"$default_instance":e).toLowerCase();if(
!Object.prototype.hasOwnProperty.call(n._iq,e)){n._iq[e]={_q:[]};v(n._iq[e])}
return n._iq[e]};e.amplitude=n})(window,document);
amplitude.getInstance().init("YOUR_API_KEY_HERE")
Using normal script tag is working fine though.
You can use <Head> tag on any page - it will automatically set <Head> to it. Don't need to modify _document or App.
We expose a built-in component for appending elements to the head of the page: (link)
And about the script - I had the same problem. My solution (possible bad)
Inside your component (for script needs to be refreshed):
useEffect(() => {
const srcUrl = `/js/analytics/amplitude.js`;
const s = document.createElement('script');
const addScript = src => {
s.setAttribute('src', src);
s.setAttribute('async', 'async');
s.setAttribute('defer', 'defer');
s.setAttribute('id', 'specific_id')
document.body.append(s);
s.remove()
};
addScript(srcUrl)
},[]);
Or in App(for "static" scripts):
const App = ({ Component, pageProps }) => (
<>
<Script
src="/js/analytics/amplitude.js"
strategy="beforeInteractive"
/>
<Component {...pageProps} />
</>
);
I use react.
for add stimulsoft reports.js, first add necessary link to css and javascript files in my Index.html file :
<link href="Css/stimulsoft.viewer.office2013.whiteblue.css" rel="stylesheet" />
<script src="Scripts/stimulsoft.reports.js"></script>
<script src="Scripts/stimulsoft.reports.maps.js"></script>
<script src="Scripts/stimulsoft.viewer.js"></script>
After that i create a Component with this code :
import React from 'react';
class Viewer extends React.Component {
render() {
return <div id="viewerContent"></div>;
}
componentWillMount() {
var report = new window.Stimulsoft.Report.StiReport();
//create error
report.loadFile("MyReportFile.mrt");
var options = new window.Stimulsoft.Viewer.StiViewerOptions();
this.viewer = new window.Stimulsoft.Viewer.StiViewer(options, "StiViewer", false);
this.viewer.report = report;
}
componentDidMount() {
this.viewer.renderHtml("viewerContent");
}
}
export default Viewer;
and loadFile method caused below error in console :
stimulsoft.reports.js:73 [Deprecation] Synchronous XMLHttpRequest on the main thread is
deprecated because of its detrimental effects to the end user's experience. For more help, check
https://xhr.spec.whatwg.org/.
Unexpected token < in JSON at position 0
Uncaught TypeError: Cannot read property 'isDashboard' of undefined
at stimulsoft.viewer.js:11
How to fix this error?
I reached the Stimulsoft report in reactjs by this two steps :
First step - Add Stimulsoft report Js files in HTML file in the public folder :
Index.html
<!DOCTYPE HTML>
<html lang="fa" dir="rtl">
<head>
<!-- Title -->
<!-- Favicon & Manifest -->
<link href="%PUBLIC_URL%/reports/stimulsoft/stimulsoft.viewer.office2013.whiteblue.css"
rel="stylesheet"
/>
<script src="%PUBLIC_URL%/reports/stimulsoft/stimulsoft.reports.engine.js" type="text/javascript"></script>
<script src="%PUBLIC_URL%/reports/stimulsoft/stimulsoft.reports.export.js" type="text/javascript"></script>
<script src="%PUBLIC_URL%/reports/stimulsoft/stimulsoft.reports.import.xlsx.js" type="text/javascript"></script>
<script src="%PUBLIC_URL%/reports/stimulsoft/stimulsoft.reports.chart.js" type="text/javascript"></script>
<!-- <script src="%PUBLIC_URL%/reports/stimulsoft/stimulsoft.dashboards.js" type="text/javascript"></script> -->
<script src="%PUBLIC_URL%/reports/stimulsoft/stimulsoft.blockly.js" type="text/javascript"></script>
<script src="%PUBLIC_URL%/reports/stimulsoft/stimulsoft.viewer.js" type="text/javascript"></script>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
</body>
</html>
Second step - create jsx component and copy this code to the component :
Viewer.jsx:
import React, { useEffect } from "react";
export default (props) => {
useEffect(() => {
if (props.show == true) {
var options = new window.Stimulsoft.Viewer.StiViewerOptions();
// options.appearance.fullScreenMode = true;
// options.height = "100%";
// options.appearance.scrollbarsMode = true;
// options.toolbar.showDesignButton = true;
var viewer = new window.Stimulsoft.Viewer.StiViewer(
options,
"StiViewer",
false
);
var report = new window.Stimulsoft.Report.StiReport();
report.licenseKey = "licenseKey ";
report.loadFile(props.templateFile);
var dataSet = new window.Stimulsoft.System.Data.DataSet("Demo");
dataSet.readJson(props.dataSet);
report.dictionary.databases.clear();
report.regData("Demo", "Demo", dataSet);
viewer.report = report;
viewer.renderHtml("viewer");
}
}),
[];
return (
<>
<div id="viewer"></div>
</>
);
};
I'm creating a integration with a payment service.
The payment service provides me a form with a script tag inside, I want to insert that form with script tag inside my component template,
but vue doesn't allow the insertion of tag script within a template, how can I insert that form with script tag inside my template component?
the form with checkout of payment service:
<form action="http://localhost:8081/api/v1/payment/" method="POST">
<script
src="https://www.mercadopago.com.br/integrations/v1/web-tokenize-checkout.js"
data-public-key="KEY"
data-transaction-amount="14.90">
</script>
</form>
The expected result:
My component:
<template>
<div id="dashboard">
<form action="http://localhost:8081/api/v1/payment/" method="POST">
<script
src="https://www.mercadopago.com.br/integrations/v1/web-tokenize-checkout.js"
data-public-key="KEY"
data-transaction-amount="14.90">
</script>
</form>
</div>
</template>
<script>
import { mapState } from "vuex";
export default {
data() {
return {}
},
}
</script>
You can use an element reference and vanilla JS to add the relevant tag to the dom.
<form ref="myform">
...
</form>
mounted() {
let foo = document.createElement('script');
foo.setAttribute("src","https://www.mercadopago.com.br/integrations/v1/web-tokenize-checkout.js");
foo.setAttribute("data-transaction-amount", "14.90")
this.$refs.myform.appendChild(foo);
}
I know this is a bit old but I came across with this problem with MercadoPago and TommyF's answer really solved it. But in my case the data-transaction-amount needed to be updated dynamically depending on users choices... So if anyone facing this, my workaround was to put it inside updated(), set an id to script tag and verify if id exists. Existing, I remove by id and all .mercadopago-button. PS: I'm newbie on JS and Vue.
let existingScript = document.getElementById('mpScript');
let existingButtons = document.getElementsByClassName('mercadopago-button');
if(existingScript) {
existingScript.remove();
while(existingButtons.length > 0) {
existingButtons[0].parentNode.removeChild(existingButtons[0]);
}
}
let script = document.createElement('script');
script.setAttribute("src", "https://www.mercadopago.com.br/integrations/v1/web-tokenize-checkout.js");
script.setAttribute("data-transaction-amount", this.total);
script.setAttribute("data-public-key", 'KEY');
script.setAttribute("id", "mpScript");
this.$refs.mpCheckout.appendChild(script);
I'm trying to load a Trading View Widget inside a react component. I tried using _dangerouslySetInnerHTML, however, it doesn't run the javascript code.
I also tried this:
import React from 'react';
export default class TradingView extends React.Component{
constructor(props){
super(props);
}
componentDidMount() {
const tradingViewCode = '<!-- TradingView Widget BEGIN --><script type="text/javascript" src="https://d33t3vvu2t2yu5.cloudfront.net/tv.js"></script><script type="text/javascript">new TradingView.widget({"autosize": true,"symbol": "BITFINEX:BTCUSD","interval": "D","timezone": "America/New_York","theme": "White","style": "1","locale": "en","toolbar_bg": "#f1f3f6","enable_publishing": false,"hide_top_toolbar": true,"save_image": false,"hideideas": true});</script><!-- TradingView Widget END -->';
new Function(tradingViewCode)();
}
render(){
return (
<noscript />
);
}
}
One way could be to create & append those script elements to your <head> in componentDidMount like this:
componentDidMount() {
var headElem = document.getElementsByTagName('head')[0];
var tradingWidgetSource = document.createElement('script');
tradingWidgetSource.type = "text/javascript";
tradingWidgetSource.src = "https://d33t3vvu2t2yu5.cloudfront.net/tv.js";
headElem.appendChild(tradingWidgetSource);
var tradingWidgetInitCode = document.createElement('script');
tradingWidgetInitCode.type = "text/javascript";
tradingWidgetInitCode.innerHTML = 'new TradingView.widget({"autosize": true,"symbol": "BITFINEX:BTCUSD","interval": "D","timezone": "America/New_York","theme": "White","style": "1","locale": "en","toolbar_bg": "#f1f3f6","enable_publishing": false,"hide_top_toolbar": true,"save_image": false,"hideideas": true});';
headElem.appendChild(tradingWidgetInitCode);
}
Unsure what your _dangerouslySetInnerHTML code was, but have used it before in render() to achieve similar goals; generally would dangerouslySetInnerHTML the JS into the <script> element:
render(){
<div>
<script dangerouslySetInnerHTML={{ __html: MyJSCodeAsString }}></script>
</div>
}
Theoretically, should be able to do something like:
render(){
<div>
<script type="text/javascript" src="https://d33t3vvu2t2yu5.cloudfront.net/tv.js" />
<script type="text/javascript" dangerouslySetInnerHTML={{ __html: 'new TradingView.widget({"autosize": true,"symbol": "BITFINEX:BTCUSD","interval": "D","timezone": "America/New_York","theme": "White","style": "1","locale": "en","toolbar_bg": "#f1f3f6","enable_publishing": false,"hide_top_toolbar": true,"save_image": false,"hideideas": true});' }}></script>
</div>
}
I'm trying to convert a project to use requirejs instead of the solution I have below. Currently I have a layout page that contains all of the scripts at the bottom of the page (except modernizr) before the tag like this:
<head>
<script src="#Links.Assets.Scripts.Libraries.modernizr_2_6_2_js"></script>
</head>
<body>
<!-- Page content goes here -->
#RenderSection("PreScripts", false)
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="#Links.Assets.Scripts.Libraries.jquery_1_9_1_min_js"><\/script>')</script>
<script src="#Links.Assets.Scripts.Libraries.jquery_namespace_js"></script>
<script src="#Links.Assets.Scripts.Libraries.jquery_unobtrusive_ajax_js"></script>
<script src="#Links.Assets.Scripts.Libraries.jquery_validate_js"></script>
<script src="#Links.Assets.Scripts.Libraries.jquery_validate_unobtrusive_js"></script>
<script src="#Links.Assets.Scripts.Libraries.jquery_timeago_js"></script>
<script src="#Links.Assets.Scripts.Libraries.toastr_js"></script>
<script src="#Links.Assets.Scripts.Views.Shared._master_js"></script>
#RenderSection("PostScripts", false)
#{
var errorMessage = TempData[TempDataConstants.ErrorMessage] as string;
var infoMessage = TempData[TempDataConstants.InfoMessage] as string;
var successMessage = TempData[TempDataConstants.SuccessMessage] as string;
if (!string.IsNullOrEmpty(errorMessage)) {
<script>
var origTimeOut = toastr.options.timeOut;
toastr.options.timeOut = 0;
toastr.error(#Html.Raw(Json.Encode(errorMessage)));
toastr.options.timeOut = origTimeOut;
</script>
}
if (!string.IsNullOrEmpty(successMessage)) {
<script>
var origTimeOut = toastr.options.timeOut;
toastr.options.timeOut = 0;
toastr.success(#Html.Raw(Json.Encode(successMessage)));
toastr.options.timeOut = origTimeOut;
</script>
}
if (!string.IsNullOrEmpty(infoMessage)) {
<script>
var origTimeOut = toastr.options.timeOut;
toastr.options.timeOut = 0;
toastr.info(#Html.Raw(Json.Encode(infoMessage)));
toastr.options.timeOut = origTimeOut;
</script>
}
}
</body>
In the individual pages that use this layout page I then populate the PostScripts section:
#section PostScripts {
// Javascript that belongs to a single page goes here.
}
Problems
I've followed this example but as you can see where I'm checking TempData on the server to see if its not null to popup a toastr message on the client. I"m not really sure the best way to go about doing this and have tried many things. Any ideas?