Message origin must match parent origin! error JavaScript - javascript

I am getting an error when loading JavaScript file to Webview.
[chromium] [INFO:CONSOLE(7)] "Message origin must match parent origin!", source: https://service.force.com/embeddedservice/5.0/eswFrame.min.js (7)
This is my JS file
<html>
<body>
<button onclick="Chat1()">Submit</button>
<script type='text/javascript' src='https://service.force.com/embeddedservice/5.0/esw.min.js'></script>
<script type='text/javascript'>
function Chat1() {
try {
var initESW = function (gslbBaseURL) {
embedded_svc.settings.displayHelpButton = true; //Or false
embedded_svc.settings.language = ''; //For example, enter 'en' or 'en-US'
embedded_svc.settings.enabledFeatures = ['LiveAgent'];
embedded_svc.settings.entryFeature = 'LiveAgent';
console.log("inside initESW- ", gslbBaseURL);
embedded_svc.init(
'https://ulr.my.salesforce.com',
'https:/ulr.force.com/visualforce',
gslbBaseURL,
'00D00055uj',
'US_Universities',
{
'baseLiveAgentContentURL': 'https://c.la3-c1cs-cdg.salesforceliveagent.com/content',
'deploymentId': '5720Q008Oqg',
'buttonId': '5730Q000PID',
'baseLiveAgentURL': 'https://d.la3-c1cs-cdg.salesforceliveagent.com/chat',
'eswLiveAgentDevName': 'EmbeddedServiceLiveAgent_Q00000000jLUAQ_17d9a605e8e',
'isOfflineSupportEnabled': false
}
);
};
if (!window.embedded_svc) {
var s = document.createElement('script');
console.log("Control here1", s);
var MinFile = 'https://ulr.my.salesforce.com/embeddedservice/5.0/esw.min.js/'
console.log("Control here2")
s.src = MinFile;
s.crossOrigin = 'anonymous';
s.onload = function () {
initESW(null);
}
document.body.appendChild(s);
}
else {
initESW('https://service.force.com');
}
}
}
</script>
</body>
</html>
How can I fix this issue ?

For me issue was, I was using html file from Assets folder and assigning content on webview but the data (html+JS) should come from URL and that should rendered on webview.

Related

Gatsby embed forms with script tag in react-helmet

I am trying to embed some forms using react helmet.
My code looks like this:
<Helmet>
<script type="text/javascript">
{var FORMID;
(function(d, t) {
var s = d.createElement(t), options = { 'userName':'USERNAME', 'formHash':'FORMID', 'autoResize':true, 'height':'751', 'async':true, 'host':'wufoo.com', 'header':'show', 'ssl':true };
s.src = ('https:' == d.location.protocol ?'https://':'http://') + 'secure.wufoo.com/scripts/embed/form.js';
s.onload = s.onreadystatechange = function() {
var rs = this.readyState;
if (rs) if (rs != 'complete') if (rs != 'loaded') return;
try {
FORMID = new WufooForm();
FORMID.initialize(options);
FORMID.display();
} catch (e) { }
};
var scr = d.getElementsByTagName(t)[0], par = scr.parentNode;
par.insertBefore(s, scr);
})(document, 'script');}
</script>
</Helmet>
The script is a copy and paste from wufoo form builder. (I replaced the username and form id with the all caps FORMID and USERNAME).
I keep running into errors. Right now this will produce a graphql error (there is not graphql in the page)
There was a problem parsing "/../my-page"; any GraphQL
fragments or queries in this file were not processed.
This may indicate a syntax error in the code, or it may be a file type
that Gatsby does not know how to parse.
and a Module build failed error.
In VS code I get some warnings on the var's saying expression expected. And some other spots where it expects a { or a }. I'm pretty certain the brackets all match up. Again, it's copy and paste from wufoo and this works in plain html/js.
Wrap your script with backticks (`):
<Helmet>
<script type="text/javascript">
{`var FORMID;
(function(d, t) {
var s = d.createElement(t), options = { 'userName':'USERNAME', 'formHash':'FORMID', 'autoResize':true, 'height':'751', 'async':true, 'host':'wufoo.com', 'header':'show', 'ssl':true };
s.src = ('https:' == d.location.protocol ?'https://':'http://') + 'secure.wufoo.com/scripts/embed/form.js';
s.onload = s.onreadystatechange = function() {
var rs = this.readyState;
if (rs) if (rs != 'complete') if (rs != 'loaded') return;
try {
FORMID = new WufooForm();
FORMID.initialize(options);
FORMID.display();
} catch (e) { }
};
var scr = d.getElementsByTagName(t)[0], par = scr.parentNode;
par.insertBefore(s, scr);
})(document, 'script');`}
</script>
</Helmet>

Context When Loading JS File Dynamically [duplicate]

I am a JavaScript newbie and learn by working on a pure JavaScript "project" that calculates mathematical functions. It all works well. Now, as a further step, I want to make the messaging multilingual. The code should be capable of loading the appropriate language file at runtime. For the dynamic loading issue, I read and found solutions on Web pages like this one.
Before writing the dynamic code, I loaded it statically and the test code worked well. The code I am asking for help about is just making the minor difference of loading a "script" element.
The code where I run into problems is the this.getString function, where it is not possible to access the de element in the language file. At line console.log(eval(language, tag));, I get the error message "Uncaught ReferenceError: de is not defined".
//File: Utils/Lang/js/FileUtils.js
function Language(language) {
var __construct = function(dynamicLoad) {
if (typeof language == 'undefined') {
language = "en";
}
// Load the proper language file:
loadFile("js/resources/lang.de.js");
return;
} ()
this.getString = function(tag, strDefault) {
console.log("getString(" + tag + ", " + strDefault + "): ");
console.log("getString(...): document = " + document);
console.log("getString(...): eval(" + language + ", " + tag + ") = ");
console.log(eval(language, tag));
var strReturn = eval('eval(language).' + tag);
if (typeof strReturn != 'undefined') {
return strReturn;
} else {
return (typeof strDefault != 'undefined')
? strDefault
: eval('en.' + tag);
}
}
}
The static test code that works is not included, where I can access the de element.
My question: How to load the language file properly so that the de tag is accessible?
Thank you for your help!
//File: Utils/Files/js/FileUtils.js
function loadFile(filepathname) {
var reference = document.createElement('script');
reference.setAttribute("type", "text/javascript");
reference.setAttribute("src", filepathname);
if (typeof reference != 'undefined') {
document.getElementsByTagName("head")[0].appendChild(reference);
}
console.log("loadFile(\"" + filepathname + "\"): document = " + document);
}
//File: Utils/Lang/js/resources/lang.de.js:
de = {
pleaseWait: "Bitte warten..."
};
//File: Utils/Lang/js/resources/lang.en.js
en = {
pleaseWait: "Please wait..."
};
//File: Utils/Lang/js/TestLanguage.js:
function output() {
console.log("output()");
var codes = ['de', 'en'];
for (var i = 0; i < codes.length; i++) {
var translator = new Language(codes[i]);
var message = "output(): in " + translator.getLanguage() + ": ";
message += translator.getString('pleaseWait');
console.log(message);
}
}
<!--File: Utils/Lang/TestLang.html:-->
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test languages</title>
<script type="text/javascript" src="../Files/js/FileUtils.js"></script>
<script type="text/javascript" src="js/Language.js"></script>
<script type="text/javascript" src="js/TestLanguage.js"></script>
</head>
<body>
<button name="outputButton" onclick="output();">Click</button>
<br>Please press [F12] so that you can see the test results.
</body>
</html>
When you add the script tag to your document, it is not loaded synchronously. You need to wait for the file to be loaded before you can use the code that was in it.
you may be able to redesign your code to use a script.onload callback:
var reference = document.createElement('script');
// ...
reference.onload = function() {
alert("Script loaded and ready");
};
but for this scenario, if you don't have many language string you may be best to just load them all statically.
How to dynamically load a script file (the most basic version, also there are multiple options to this):
function loadScriptFile(scriptPath, jsFile, callBack)
{
var scriptTag = document.createElement("script"); //creates a HTML script element
scriptTag.language = "JavaScript"; //sets the language attribute
scriptTag.type = "text/javascript";
scriptTag.src = scriptPath + jsFile + ".js"; //the source
if (callBack)
{
scriptTag.onload = callback; //when loaded execute call back
}
var scriptTagParent = document.getElementsByTagName("script")[0];
if (scriptTagParent)
{
scriptTagParent.parentNode.insertBefore(scriptTag, scriptTagParent);
}
else
{
document.body.appendChild(scriptTag);
}
}
How it works:
Run loadScriptFile("scripts", "math", startProgram). The first two arguments will point to your file and folder. The last argument is a callback function. When defined this will be executed once the script tag has finished loading and the script is available in the global scope. The script will be dynamically added to your page. If there is a script element present on the page, this will be added before that (to keep the mark up nice). If not it will be appended to the body. (this is only visual).
The callback part is the most interesting. Since your script will now be asynchronical, you'll need to use callback to tell your program that the necessary files are loaded. This callback is fired when the script file is loaded, so you won't get script errors.
Just a basic example of what I meant in my comment:
This is not an answer to your question, it's an alternative way (I think it's better to manage). Pure Javascript (with help of XML)
XML-file: language.xml
Basic XML structure:
<language>
<l1033 name="english" tag="en-US">
<id1000>
<![CDATA[
Hello World!
]]>
</id1000>
</l1033>
<l1031 name="german" tag="de-DE">
<id1000>
<![CDATA[
Hallo Welt!
]]>
</id1000>
</l1031>
</language>
What did I do:
I constructed a root element called language. Within that wrote two language strings called l1033 for English and l1031 for German. Note that a letter is prepended before the language code. XML will throw an error when a tag starts with a digit. a CDATA block is used to prevent any problems with special characters.
Now the loading will be done by AJAX:
var xmlLoader = new XMLHttpRequest();
xmlLoader.onreadystatechange = trackRequest; //event to track the request, with call back
xmlLoader.open("get", "language.xml", true); //set asynchronous to true
xmlLoader.send(null);
function trackRequest()
{
if (this.status == 200 && this.readyState == 4) //all is good
{
globalLanguageFile = this.responseXML;
startProgram(); //fictive function that starts your program
}
}
Now the XML is loaded. How to load strings from it?
function loadLanguageString(code, id, fallback)
{
var word = fallback;
if (globalLanguageFile.getElementsByTagName("l"+code).length > 0)
{
if (globalLanguageFile.getElementsByTagName("l"+code).[0].getElementsByTagName("id"+id).length > 0)
{
//found the correct language tag and id tag. Now retrieve the content with textContent.
word = globalLanguageFile.getElementsByTagName("l"+code).[0].getElementsByTagName("id"+id)[0].textContent;
}
}
return word; //when failed return fall back string
}
How to call the function:
loadLanguageString(1031, 1000, "Hello World!");
I found the right answer to my question using the info from GarethOwen. Here are the code modifications I had to do:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Test languages</title>
<script type="text/javascript" src="../Arrays/js/ArrayUtils.js"></script>
<script type="text/javascript" src="../Files/js/FileUtils.js"></script>
<script type="text/javascript" src="../Logic/js/LogicalUtils.js"></script>
<script type="text/javascript" src="js/LanguageUtils.js"></script>
<script type="text/javascript" src="js/TestLanguageUtils.js"></script>
</head>
<!-- body onload="load(null, '../Maths/js/resources')" -->
<body onload="load();">
<button onclick="output();">Click</button><br>
Please press [F12] so that you can see the test results.
</body>
</html>
TestLanguage.html: Augmented the body tag
<body onload="load()">
TestLanguage.js:
2a. Added the load() function requested by the HTML page now:
var gCodes = ['de', 'en', 'tr'];
function load() {
console.log("load()");
for (var i = 0; i < codes.length; i++) {
new Language(codes[i]);
}
}
2b. Using the global gCodes variable also in the output() function
Language.js: To test the whole better, I made the code in the function Language a little bit more elaborate by changing the line in the constructor in function Language(language) to:
// Load the proper language file:
if (eval("gLoaded.indexOf('" + language + "') < 0")) {
loadFile("js/resources/lang." + language + ".js");
gLoaded[gLoaded.length] = language;
}
Thank you for your support! :-)
//Lang/js/Lang.js:
"use strict";
/**
* Object for multilingual message handling.
*
* #param language
*/
function Language(language) {
var __construct = function(dynamicLoad) {
if (typeof language == 'undefined') {
language = "en";
}
// Load the proper language file:
switch (language) {
case "de":
loadFile("js/resources/lang.de.js");
break;
case "tr":
loadFile("js/resources/lang.tr.js");
break;
default:
loadFile("js/resources/lang.en.js");
}
return;
}()
/**
* Returns the language of that object.
*
* #returns The language
*/
this.getLanguage = function() {
var strLanguage;
switch (language) {
case "de":
strLanguage = "German";
break;
case "tr":
strLanguage = "Turkish";
break;
default:
strLanguage = "English";
}
return strLanguage;
}
/**
* Returns the language code of that object.
*
* #returns The language code
*/
this.getString = function(tag, strDefault) {
var strReturn = eval('eval(language).' + tag);
if (typeof strReturn != 'undefined') {
return strReturn;
} else {
return (typeof strDefault != 'undefined') ? strDefault : eval('en.' + tag);
}
}
}
//Lang/js/TestLang.js:
"use strict";
var gCodes = ['de', 'en', 'tr'];
function load() {
console.log("load()");
for (var i = 0; i < gCodes.length; i++) {
new Language(gCodes[i]);
}
}
/**
* Object for multilingual message handling.
*
* #param language
*/
function output() {
console.log("output()");
for (var i = 0; i < gCodes.length; i++) {
var translator = new Language(gCodes[i]);
var message = "output(): in " + translator.getLanguage() + ": ";
message += translator.getString('pleaseWait');
console.log(message);
}
}
//Utils/Files/js/FileUtils.js:
"use strict";
/**
* Object with file utilities
*
* #param filepathname
*/
function loadFile(filepathname) {
var methodName = "loadFile(" + filepathname + "): "
var reference = document.createElement('script');
reference.setAttribute("type", "text/javascript");
reference.setAttribute("src", filepathname);
if (typeof reference != 'undefined') {
document.getElementsByTagName("head")[0].appendChild(reference);
}
reference.onload = function() {
console.log(methodName + "onload(): Language script loaded and ready!");
}
}
Here is the console output:
Here is the output:
load()
loadFile(js/resources/lang.de.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.en.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.tr.js): onload(): Language script loaded and ready!
output()
output(): in German: Bitte warten...
output(): in English: Please wait...
output(): in Turkish: Lütfen bekleyiniz...
loadFile(js/resources/lang.de.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.en.js): onload(): Language script loaded and ready!
loadFile(js/resources/lang.tr.js): onload(): Language script loaded and ready!

Chrome extension : Stuck at injecting script won't execute js

I am trying to build a chrome extension. Which would do some search on the page and post the results to the extensions.
I am having a hard time running this. Whenever I try to run the extension it is just stuck on Injecting Script.
my re.js
function printDetails(document_r) {
var test = document_r.body;
var text = test.innerText;
var delim="^^ validatedCache :";
var endlim="</site>";
var idx = text.indexOf(delim);
var endInd=text.indexOf(endlim);
var tag = "accountName";
var regex = "<" + tag + ">(.*?)<\/" + tag + ">";
var regexg = new RegExp(regex,"g");
var matches = [];
while (match = regexg.exec(text.substring(idx+delim.length,endInd))) matches.push("Account Name::::::"+match[1]);
return matches;
}
chrome.extension.sendMessage({
action: "getSource",
source: "\n\n\n DETAILS>>>>>\n\n"+printDetails(document)
});
selection.js
chrome.extension.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
message.innerText = request.source;
}
});
function onWindowLoad() {
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {
file: "re.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.extension.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.extension.lastError.message;
}
});
}
window.onload = onWindowLoad;
popup.html
<!DOCTYPE html>
<html style=''>
<head>
<script src='selection.js'></script>
</head>
<body style="background-image:url(12.png);width:400px; border: 2px solid black;background-color:white;">
<div id='message'>Injecting Script....</div>
</body>
</html>
I know there is some problem with these 2 lines only.
var test = document_r.body;
var text = test.innerText;
What I wan't is to extract the webpage ( contents ) into a string which I am hopefully doing by the above two lines of code.
Then do some string manipulation on the code.If I run directly this code in a console with a dummy string . I can execute it so figure something is wrong with these two lines.
My extension is stuck on " Injecting Script..."
Some help would be appreciated.
PS:yes I was able to run it earlier with the same code but somehow it doesn't run now.

missing } in xml expression and exce_next

my javascript function is throwing this error
var cycles = 0;
var exec_next = null;
function timer_interrupt() {
cycles++;
if (exec_next) {
var cmd = exec_next;
exec_next = null;
cmd();
}
}
using firebug it says the } should be at the end of the cycles++; what to do? I don't have any xml script being displayed?
it is being included in my template like this
<script language="JavaScript" src="mysript.js">
</script>

Running script tags fetched with jsonp

Edit: Resolved, see answer below.
The problem I'm trying to solve is an ad loading script, that loads the ad code with jsonp and inserts it into the dom.
Now sometimes the ad code will include javascript tags, and from some posts here on stackoverflow i got the idea that moving them to head of the document to make them run, which after some experimentation prompted me to ask this question:
Appending scripts to head using javascript - weird behavior
My question there was solved but the problem remains, the scripts i insert into my test div does not run, nor do they run when moved to the head.
I have a code example here:
http://m.iijax.com/p1.html
And a simple jsonp example here:
http://m.iijax.com/p2.php
The code in p2 will try to log a message to the console, alert a message, and set a variable which i then try to print out, and all of these things fails.
Is the only way to run code like this using the eval function or am I doing some basic mistake?
Here is the code for the first part:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
if (typeof JSONP === 'undefined') {
/*Lightweight JSONP fetcher - www.nonobtrusive.com*/
var JSONP = (function(){
var counter = 0, head, query, key, window = this;
function load(url) {
var script = document.createElement('script'),
done = false;
script.src = url;
script.async = true;
script.onload = script.onreadystatechange = function() {
if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) {
done = true;
script.onload = script.onreadystatechange = null;
if ( script && script.parentNode ) {
script.parentNode.removeChild( script );
}
}
};
if ( !head ) {
head = document.getElementsByTagName('head')[0];
}
head.appendChild( script );
}
function jsonp(url, params, callback) {
query = "?";
params = params || {};
for ( key in params ) {
if ( params.hasOwnProperty(key) ) {
query += encodeURIComponent(key) + "=" + encodeURIComponent(params[key]) + "&";
}
}
var jsonp = "json" + (++counter);
window[ jsonp ] = function(data){
callback(data);
window[ jsonp ] = null;
try {
delete window[ jsonp ];
} catch (e) {}
};
load(url + query + "callback=" + jsonp);
return jsonp;
}
return {
get:jsonp
};
}());
}
JSONP.get( 'http://m.iijax.com/p2.php', { requestType:'demoRequest'}, function(data){
var adC = document.getElementById("testId");
adC.innerHTML = data.code;
// Move script tags to head
var scripts = adC.getElementsByTagName("script");
for(i=scripts.length - 1;i>-1;i--) {
document.head.appendChild(scripts[i]);
}
// Now check value of var letsSeeIfThisIsDefined, set in the fetched code
console.log(letsSeeIfThisIsDefined);
});
</script>
</head>
<body>
<div id="testId"></div>
</body>
</html>
The answer seems a little bloated. Here's my version:
function execJSONP(url, cb) {
var script = document.createElement('script');
script.async = true;
var callb = 'exec'+Math.floor((Math.random()*65535)+1);
window[callb] = function(data) {
var scr = document.getElementById(callb);
scr.parentNode.removeChild(scr);
cb(data);
window[callb] = null;
delete window[callb];
}
var sepchar = (url.indexOf('?') > -1)?'&':'?';
script.src = url+sepchar+'callback='+callb;
script.id = callb;
document.getElementsByTagName('head')[0].appendChild(script);
}
Thanks to this post:
Executing <script> elements inserted with .innerHTML
I was able to modify my code a little, I now pick out the data from the script tags fetched with jsonp, put it into newly created script tags and append them to the head and it works. :)
Here is the revised code, including the new function parseScripts():
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function parseScripts(elementId) {
// Get the div where code has been inserted by innerHTML
var td = document.getElementById(elementId);
// Find any script tags in that code
var scripts = td.getElementsByTagName("script");
for(i=scripts.length - 1;i>-1;i--) {
// For each script found pick out the data
var elem = scripts[i];
var data = (elem.text || elem.textContent || elem.innerHTML || "" );
// Create a new script element and add the data
var script = document.createElement("script");
script.type = "text/javascript";
try {
// doesn't work on ie...
script.appendChild(document.createTextNode(data));
} catch(e) {
// IE has funky script nodes
script.text = data;
}
// Append new script tag to head of document
document.head.appendChild(script);
}
}
if (typeof JSONP === 'undefined') {
/*Lightweight JSONP fetcher - www.nonobtrusive.com*/
var JSONP = (function(){
var counter = 0, head, query, key, window = this;
function load(url) {
var script = document.createElement('script'),
done = false;
script.src = url;
script.async = true;
script.onload = script.onreadystatechange = function() {
if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) {
done = true;
script.onload = script.onreadystatechange = null;
if ( script && script.parentNode ) {
script.parentNode.removeChild( script );
}
}
};
if ( !head ) {
head = document.getElementsByTagName('head')[0];
}
head.appendChild( script );
}
function jsonp(url, params, callback) {
query = "?";
params = params || {};
for ( key in params ) {
if ( params.hasOwnProperty(key) ) {
query += encodeURIComponent(key) + "=" + encodeURIComponent(params[key]) + "&";
}
}
var jsonp = "json" + (++counter);
window[ jsonp ] = function(data){
callback(data);
window[ jsonp ] = null;
try {
delete window[ jsonp ];
} catch (e) {}
};
load(url + query + "callback=" + jsonp);
return jsonp;
}
return {
get:jsonp
};
}());
}
JSONP.get( 'http://m.iijax.com/p2.php', { requestType:'demoRequest'}, function(data){
var adC = document.getElementById("testId");
adC.innerHTML = data.code;
// Try and run the scripts
parseScripts("testId");
});
</script>
</head>
<body>
<div id="testId"></div>
<div style="height: 0px; width: 0px; border: 10px solid transparent; border-left-color: #505050;"></div>
</body>
</html>

Categories

Resources