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

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.

Related

signalR undefined but signalr.js is loaded in the debugger

I am trying to use SignalR for ASP.NET Core 2.0, but when I try to implement the SignalR client in my View, I get the error that the variable "signalR" is undefined despite auto-completion working fine in my editor, Here is the script :
<script type="text/javascript">
var _transport = signalR.TransportType.WebSockets; //HERE
var connection = new signalR.HubConnection(`http://${document.location.host}/chat`, {transport: _transport});
var messageInput = document.getElementById('message');
var name = '#User.Identity.Name';
var button = document.getElementById('sendMessage');
connection.on('broadcastMessage', (name, message) => {
var text = document.createElement('p');
text.innerHTML = '<strong>' + name + '</strong>' + " : " + message;
document.getElementById('messageArea').appendChild(text);
});
button.addEventListener("click", event => {
connection.invoke('send', name, messageInput.value);
messageInput.value = '';
messageInput.focus();
});
connection.start();
I have added the signalr.js in my _Layout.cshtml
Here is the tree structure of my wwwroot where I've added the .js files for signalr :
And finally, here is the debugger structure in Firefox where I can see that the signalr.js has been loaded, and so are jQuery and bootstrap..
So why is "signalR" undefined? What am I missing? Is it because I've added the signalr javascript files manually in my project? (Probably...)
I think your script is executed before the signalr.js is loaded. Try to use an event to execute your code. IF we do this on document load then we'll be sure that it's defined.
$(document).load(function(){
// your code here
});

PhantomJS get JS refresh

I need to check every content change on a web site.
I wrote a PhantomJS function to get the whole web site. After receiving the web site I parse every row to get the data.
Now I want to hold the connection and receive all JS-updates.
What need I do to get the JS-updates?
I hope my question is clear.
Here some code explanations:
Pseudo HTML Website
<html>
<head>...</head>
<body>
<div class="value-123" onload="(function() { setInterval(retrieveData(...), 5000); })">
<!-- If retrieveData finished, VALUE will change from e.g. 1.23 to 4.235 -->
VALUE
</div>
</body>
</html>
My PhantomJS Code:
const string cEndLine = "All output received";
var sb = new StringBuilder();
var p = new PhantomJS();
p.OutputReceived += (sender, e) =>
{
if (e.Data == cEndLine)
{
callBack(sb.ToString());
}
else
{
sb.AppendLine(e.Data);
}
};
p.RunScript(#"
var page = require('webpage').create();
page.settings.loadImages = false;
page.viewportSize = { width: 1920, height: 1080 };
page.onLoadFinished = function(status) {
if (status=='success') {
setTimeout(function() {
console.log(page.content);
console.log('" + cEndLine + #"');
phantom.exit();
}," + waitAfterPageLoad.TotalMilliseconds + #");
}
};
var url = '" + url + #"';
page.open(url);", new string[0]);

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!

Using HTML Tags in Wordpress Page. Getting Error: "Unexncaught SyntaxError..."

I am retrieving data from Parse in my Wordpress page fine. I can append the names of my objects into a page in Wordpress, but as soon as a try to append a HTML tag like <h1> or <p>, I get an error within my Chrome console:
Uncaught SyntaxError: Unexpected token ILLEGAL
Below is the code within my wordpress page that works without errors:
<div id="list1"><h1>Beer List</h1></div>
<div id="list2"><h1>Tap List</h1></div>
<script type="text/javascript">
if (typeof jQuery != 'undefined') {
Parse.initialize("", "");
var Objs = Parse.Object.extend("Obj");
var query = new Parse.Query(Objs);
query.ascending("name");
query.find({
success: function(results) {
var obj1String = '';
var obj2String = '';
for(var i=0;i<results.length;i++)
{
var object = results[i];
obj1String= obj1String +' '+object.get('name')+'</br>';
if(object.get('isObj2') == true){
obj2String = obj2String +' '+object.get('name')+'</br>';
}
}
jQuery( "#list1" ).append( obj1String );
jQuery( "#list2" ).append( obj2String );
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
</script>
But when I add, for example a tag to one of my objStrings, I get the error. i.e.:
obj1String= obj1String +'<h1>'+object.get('name')+'</h1></br>';
Here is how the page is rendering, any why the error is happening. It seems to be adding a line break when it sees those tags:
for(var i=0;i<results.length;i++)
{
var object = results[i];
obj1String= obj1String +' //line break added here
<h1>'+object.get('name')+'</h1>
<p></br>';
if(object.get('isObj2') == true){
objString = obj2String +' '+object.get('name')+'</br>';
}
I have see other threads for this error (i.e. here). But I could not get any suggestions there to work.
Any help would be greatly appreciated, thanks!
I've had a similar problem to this before and I fixed it by making sure all the HTML tags in the JavaScript are on the same line.
As for wordpress template files you can read more about it here http://codex.wordpress.org/Page_Templates. Simply it will allow you to use a PHP file as a template to display that page.

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>

Categories

Resources