Jump to content
Sign in to follow this  
Skitty

[JS] UserScript / Chrome Browser Extension

Recommended Posts

Skitty

I've been trying to make an extension for embedding plain text links on imageboards like 4chan.

I've taken code from a more fully featured extension that has features that I really don't want because it's incompatible with the more popular extensions out there.

I have it working as an extension in my browser, the edited full version of it, but when I pack it for installation and re-install it, it throws errors like "Uncaught TypeError: Cannot read property 'links1' of undefined".

I don't know much about JS but I'm wondering why it's not throwing this error in the original version where it's edited but throws the error on the one installed from the packed crx file.

var links = /((?:https?|ftp)://[^s'"'<>()]+|www.[^s'"'<>()]+|[-w.+]+@(?:[-w]+.)+[w]{2,6})/gi;

function apply() {
        if (!window.location.href.match(/boards./)) return false;
        var a = document.getElementsByTagName("iframe"), b = document.getElementsByTagName("embed");
        Activate(a,b);
}

function Activate(a, b) {
        a = a ? a + " " : "";
        for (var d, c = xpath((a == "" ? "." : "id('" + a.substr(1, a.length - 2) + "')") + "//text()[ancestor::blockquote]"), e = 0; e < c.snapshotLength; e++) {
            d = c.snapshotItem(e);
            d != null && linkActivation(d);
        }
}

function linkActivation(a) {
        for (var b, d, c = a.textContent, e = null, g = 0, f = {}, youtube, vocaroo, soundcloud;
        (d = links.exec(c)) !== null;) if (!f[d[0]]) {
            f[d[0]] = true;
            null === e && (e = document.createElement("span"));
            b = d[0].replace(/.*$/, "");
            e.appendChild(document.createTextNode(c.substring(g, d.index)));
            if (!b.match(/.4chan.org/i)) {
                b = (youtube = b.match(/youtube.com/watch?.*?v=([a-z0-9-_#!]+)/i)) && (settings.youtube1 != "off" && !inThread || settings.youtube2 != "off" && inThread) ? '<iframe class="youtube-player" type="text/html" width="640" height="385" src="http://www.youtube.com/embed/' + youtube[1] + '?wmode=opaque" frameborder="0"></iframe><br /><a href="' + b + '" target="_blank">' + b + "</a>" : 
                (vocaroo = b.match(/vocaroo.com/(i/|?media=)([a-z0-9]+)/i)) && (settings.vocaroo1 != "off" && !inThread || settings.vocaroo2 != "off" && inThread) ? '<object type="application/x-shockwave-flash" style="width: 148px; height: 44px" data="http://vocaroo.com/player.swf?playMediaID=' + vocaroo[2] + '&server=m1.vocaroo.com&autoplay=0""><param name="movie" value="http://vocaroo.com/player.swf?playMediaID=' + vocaroo[2] + '&server=m1.vocaroo.com&autoplay=0"></object><br /><a href="' + b + '" target="_blank">' + b + "</a>" : 
                (soundcloud = b.match(/((www.)?soundcloud.com/([a-z0-9-_]+/?)+)/i)) && (settings.soundcloud1 != "off" && !inThread || settings.soundcloud2 != "off" && inThread) ? '<object height="81" width="400"><param name="movie" value="http://player.soundcloud.com/player.swf?url=http://' + soundcloud[1] + '&amp;g=bb"></param><param name="allowscriptaccess" value="always"></param><embed allowscriptaccess="always" height="81" src="http://player.soundcloud.com/player.swf?url=http://' + soundcloud[1] + '&amp;g=bb" type="application/x-shockwave-flash" width="400"></embed></object><br /><a href="http://' + soundcloud[1] + '" target="_blank">http://' + soundcloud[1] + "</a>" : 
                b.indexOf("@") > -1 && (settings.email1 != "off" && !inThread || settings.email2 != "off" && inThread) ? "<a href='mailto:" + b + "'>" + b + "</a>" : 
                settings.links1 != "off" && !inThread || settings.links2 != "off" && inThread && b.indexOf("@") < 0 ? "<a href='" + (b.match(/^http/i) ? b : "http://" + b) + "' target='_blank'>" + b + "</a>" : b;
                e.innerHTML = b;
                g = d.index + d[0].length;
            }
        }
        if (e) {
            e.appendChild(document.createTextNode(c.substring(g, c.length)));
            try {
                a.parentNode.replaceChild(e, a);
            } catch (h) {
                console.error(h);
            }
        }
}

function xpath(a) {
        return document.evaluate(a, document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null)
}

apply();
Edited by CaptainClucks

Things that I've done..

Icon Resource Editor: icon resource editor 

AutoIt Piano: a piano

AutoIt Unlocker: unlocks files when you want to delete them

Colorful tooltips: a wrapper for the tool tips UDF

Rouge GoogleBot: a full screen animation

ASciTE text editor: a text editor written in autoit

Warning: Posts by this user are subject to change or may disappear without notice.

Share this post


Link to post
Share on other sites
jaberwacky

Th best I can grok is that settings is not defined within the linkActivation function. I'm no JS person at all but the very first line is (function () {, what's that all about?

Share this post


Link to post
Share on other sites
danielkza

Th best I can grok is that settings is not defined within the linkActivation function. I'm no JS person at all but the very first line is (function () {, what's that all about?

It declares an anonymous function, wrapped in parenthesis so you can call it right away. This:

(function (s) {
alert(s);
})("hello");

would show you a 'hello' message box.

Edited by danielkza

Share this post


Link to post
Share on other sites
jvanegmond

I hate javascript so much. JS seems so tedious and ambiguous. Am I right?

No.
  • Like 1

Share this post


Link to post
Share on other sites
Mat

So, you don't look at the code in the OP and want to die?

I can write some very ugly AutoIt if you like... In fact name me any language and I'll make you look for a knife.

Not saying I like js... I just don't like it because it's used almost entirely for web development which I don't like. Same goes for php.

Share this post


Link to post
Share on other sites
Skitty

One thing to note is that the original code that this came from was originally created in some other language that's called coffee something, I don't remember but I was reading about it and the dev seemed to mention that he converts the other language into this java script mess you see up there.


Things that I've done..

Icon Resource Editor: icon resource editor 

AutoIt Piano: a piano

AutoIt Unlocker: unlocks files when you want to delete them

Colorful tooltips: a wrapper for the tool tips UDF

Rouge GoogleBot: a full screen animation

ASciTE text editor: a text editor written in autoit

Warning: Posts by this user are subject to change or may disappear without notice.

Share this post


Link to post
Share on other sites
danielkza

I hate j&#097;v&#097;script so much. JS seems so tedious and ambiguous. Am I right?

I actually (mostly) like J&#097;v&#097;script as a language, ignoring the confusing web-browser stuff. I'm personally like writing code using anonymous and nested functions, closures, etc. It's very far from perfect though: the (lack of) a class system makes object-oriented programming much harder than it should be (that's one of the reasons CoffeeScript and other languages that compile to JS are getting popular), the weak typing system causes unexpected gotchas and weird behavior (I'm not even talking about the lack of static typing: Python has completely dynamic typing, but blows up whenever you try to mix up incompatible types instead of giving you retarded results), the (lack of proper) scoping is a mind-boggling oversight, etc.

One thing to note is that the original code that this came from was originally created in some other language that's called coffee something, I don't remember but I was reading about it and the dev seemed to mention that he converts the other language into this java script mess you see up there.

CoffeeScript is the name of the language you mention. Most of it translates in a straight-forward way to vanilla J&#097;v&#097;script: most of the converted code I see doesn't look as bad as this example. I wonder if it was actually bad CoffeeScript to begin with.

Edited by danielkza
  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Similar Content

    • Seminko
      By Seminko
      Is there a way to grab non-hardcoded but rather javascript generated data from a webpage?
      Tried a get request as well as _IEBodyReadHTML but both seem to grab the code without the javascript generated data.
      $oHTTP = ObjCreate("winhttp.winhttprequest.5.1") $oHTTP.Open("GET", "link", False) $oHTTP.Send() $oReceived = $oHTTP.ResponseText $oStatusCode = $oHTTP.Status Global $DataArray[10][5] If $oStatusCode <> 200 Then Exit MsgBox(1, "Error", "Status Code <> 200") EndIf FileWrite(@ScriptDir & "\output.txt", $oReceived) ; //////// #include <IE.au3> Local $FullLink = "link" Local $oIE = _IECreate($FullLink, 0, 0) _IELoadWait($oIE) Local $sText = _IEBodyReadHTML($oIE) FileWrite(@ScriptDir & "\output.txt", $sText)  
    • guinness
      By guinness
      Just trying out the latest version of AutoIt and thinking more functional
      #include <Array.au3> ; Example ; An example of filtering, mapping and reducing arrays, using a function reference. ; This is similiar to how it would be done in the likes of JavaScript ; i.e. more functional (declarative) than procedural (imperative) ; Filter example Local $aiFilteredBefore[] = [1, 2, 3, 50, 30, 40, 20, 30] Local $aiFilteredAfter = _ArrayFilter($aiFilteredBefore, GtrThan30) _ArrayDisplay($aiFilteredAfter, '_ArrayFilter::') ; Map example Local $aiMappedBefore[] = [1, 2, 3, 4, 5, 6, 7, 8, 9] Local $aiMappedAfter = _ArrayMap($aiMappedBefore, MultiplyByTwo) _ArrayDisplay($aiMappedAfter, '_ArrayMap::') ; Reduce example ; Sum all values in the array Local $aiReducedBefore[] = [1, 2, 3, 50, 30, 40, 20, 30] ConsoleWrite('_ArrayReduce:: ' & _ArrayReduce($aiReducedBefore, SumValues) & @CRLF) ; Passing an empty array, will return the initial value; otherwise, sets @error to 4 ; if no initial value is defined Local $aEmpty[] = [] ConsoleWrite('_ArrayReduce:: ' & _ArrayReduce($aEmpty, SumValues, 0) & @CRLF) ; Array callback functions (for the examples only) Func GtrThan30($iValue) Return $iValue > 30 EndFunc ;==>GtrThan30 Func MultiplyByTwo($iValue, $iIndex, $aiArray) ; Notice how the function is called with the optional arguments "index" and "original array" ConsoleWrite('Index:: ' & $iIndex & ', Array:: ' & _ArrayToString($aiArray) & @CRLF) Return $iValue * 2 EndFunc ;==>MultiplyByTwo Func SumValues($a, $b) Return $a + $b EndFunc ;==>SumValues ; Functions ; The callback function is invoked with fn(value, [index, [array]]) Func _ArrayFilter($avArray, $hFunc) If Not IsArray($avArray) Then ; Null is more appropriate than returning the likes of -1 or an empty array Return SetError(1, 0, Null) EndIf If Not IsFunc($hFunc) Then Return SetError(2, 0, Null) EndIf Local Const $iLength = UBound($avArray) Local $avFiltered[$iLength] If $iLength = 0 Then Return $avFiltered EndIf Local $iIndex = 0 For $i = 0 To $iLength - 1 Local $bIsFiltered = __ArrayCall($hFunc, 3, $avArray[$i], $i, $avArray) If @error Then Return SetError(@error, @extended, Null) ElseIf $bIsFiltered Then $avFiltered[$iIndex] = $avArray[$i] $iIndex += 1 EndIf Next ReDim $avFiltered[$iIndex] Return $avFiltered EndFunc ;==>_ArrayFilter ; The callback function is invoked with fn(value, [index, [array]]) Func _ArrayMap($avArray, $hFunc) If Not IsArray($avArray) Then ; Null is more appropriate than returning the likes of -1 or an empty array Return SetError(1, 0, Null) EndIf If Not IsFunc($hFunc) Then Return SetError(2, 0, Null) EndIf Local Const $iLength = UBound($avArray) Local $avMapped[$iLength] If $iLength = 0 Then Return $avMapped EndIf For $i = 0 To $iLength - 1 $avMapped[$i] = __ArrayCall($hFunc, 3, $avArray[$i], $i, $avArray) If @error Then Return SetError(@error, @extended, Null) EndIf Next Return $avMapped EndFunc ;==>_ArrayMap ; The callback function is invoked with fn(current, value, [index, [array]]) Func _ArrayReduce($avArray, $hFunc, $vInitial = Default) If Not IsArray($avArray) Then ; Null is more appropriate than returning the likes of -1 or an empty array Return SetError(1, 0, Null) EndIf If Not IsFunc($hFunc) Then Return SetError(2, 0, Null) EndIf Local $bHasInitial = @NumParams >= 3 Local $iLength = UBound($avArray) If $iLength = 0 Then If Not $bHasInitial Then Return SetError(4, 0, Null) EndIf Return $vInitial EndIf For $i = 0 To $iLength - 1 If $bHasInitial Then $vInitial = __ArrayCall($hFunc, 3, $vInitial, $avArray[$i], $i, $avArray) If @error Then Return SetError(@error, @extended, Null) EndIf Else $bHasInitial = True $vInitial = $avArray[$i] EndIf Next Return $vInitial EndFunc ;==>_ArrayReduce Func __ArrayCall($hFunc, $iError, $vArg1 = Default, $vArg2 = Default, $vArg3 = Default, $vArg4 = Default) Local Const $CALL_ERROR = 0xDEAD Local Const $CALL_EXTENDED = 0xBEEF Local $vRet = Call($hFunc, $vArg1) If @error = $CALL_ERROR And @extended = $CALL_EXTENDED Then $vRet = Call($hFunc, $vArg1, $vArg2) If @error = $CALL_ERROR And @extended = $CALL_EXTENDED Then $vRet = Call($hFunc, $vArg1, $vArg2, $vArg3) If @error = $CALL_ERROR And @extended = $CALL_EXTENDED Then $vRet = Call($hFunc, $vArg1, $vArg2, $vArg3, $vArg4) If @error = $CALL_ERROR And @extended = $CALL_EXTENDED Then ; The function exists, but there is no appropriate function signature Return SetError($iError, 0, Null) EndIf EndIf EndIf EndIf Return SetError(@error, @extended, $vRet) EndFunc ;==>__ArrayCall  
    • Seminko
      By Seminko
      In my recent project I'm downloading a bunch of data, so I decided to store it in a SQLite database. NOTE: I'm using sqlite3_x64.dll
      Everything is working just fine but I'm struggling with getting the Median value. SQLite has an Average function but not a Median one.
      I googled but all of the provided solutions are way above my pay-grade. After some more searching I found 'extension-functions.c' on the SQLite site where Median is included. After almost an hour of struggling I was able to successfully compile it into a DLL.
      So I downloaded @jchd's SQLiteExtLoad.au3 as seen here:
      But I'm getting these errors:
      "Path\SQLiteExtLoad.au3"(21,40) : warning: $g_hDll_SQLite: possibly used before declaration. Local $RetVal = DllCall($g_hDll_SQLite, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^ "Path\SQLiteExtLoad.au3"(21,40) : error: $g_hDll_SQLite: undeclared global variable. Local $RetVal = DllCall($g_hDll_SQLite, ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^ So I tried, copying the function to my file and changing the DLL variable ($g_hDll_SQLite) directly to the DLL location (C:\...\.. .dll), but now this error fires
      If __SQLite_hChk($hConn, 1) Then Return SetError(@error, 0, $SQLITE_MISUSE) To be honest, I don't know what to use as the $hConn - handle of connection.
      I would appreciate any help, be it getting the median using SQLite queries or getting the DLL extension loaded using AutoIt.
      Thanks, S.
       
      EDIT: well, I suspect the $hConn variable refers to the return value of the _SQLite_Open function. Well, at least now _SQLite_EnableExtensions doesn't give errors. Now I run into problems with _SQLite_LoadExtension, which gives error -1, and extended 1. Apparently the 1 constant is a generic error where other error do not apply.
      BTW, anybody knows whether I need to compile the extension DLL "into" x64 when I use a x64 SQLite? That might be the problem...
       
      EDIT2: I recompiled the dll and tried it using the SQLite3.exe and it works, so I'm confident the extension DLL has been created correctly

    • kjpolker
      By kjpolker
      Hello,
      I am looking for a way to essentially fullscreen a YouTube video in Chrome to the size of the window. Eliminating all chrome features, scroll bars, bookmarks, and YouTube headers, etc...
      To explain why, I wrote a simple script that forces a window to be on top, so when I am working I can have a small sized YouTube window opened playing a video. Being picky, the features of Chrome+YouTube are annoying to see. I would like the video to fulfill the window when toggling it on top and off.
      Any way to achieve this through the chrome window or will I need to create my own GUI and embed the video?
      Maybe allowing just the main features such as exit and minimize to exist? While preserving full video functionality of pause and resume.
      FROM THIS

      TO THIS

      Thanks,
    • Chimp
      By Chimp
      An example on how to inject jQuery into a web page
      It can be useful to manage the page from AutoIt using jQuery.
      Idea from here: http://www.learningjquery.com/2009/04/better-stronger-safer-jquerify-bookmarklet
      Suggestions and improvements are welcome
      #include <ie.au3> Example() Func Example() Local $oIE = _IECreate("www.google.com") Local $jQuery = _jQuerify($oIE) MsgBox(0, "Version", "jQuery version: " & $jQuery.fn.jquery) MsgBox(0, "Example", "click ok to exit." & @CRLF & "Google logo will fade out by jQuery...") $jQuery('#hplogo').fadeOut(3000) ; jQuery will fade out the google logo EndFunc ;==>Example ; #FUNCTION# ==================================================================================================================== ; Name ..........: _jQuerify ; Description ...: ; Syntax ........: _jQuerify(Byref $oIE) ; Parameters ....: $oIE - Object variable of an InternetExplorer.Application. ; Return values .: an object variable pointing to the jQuery library ; Author ........: Chimp ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........: ; Example .......: ; =============================================================================================================================== Func _jQuerify(ByRef $oIE) Local $jsEval, $jQuery, $otherlib = False ; create a reference to the javascript eval() function $oIE.document.parentWindow.setTimeout('document.head.eval = eval', 0) Do Sleep(250) $jsEval = Execute('$oIE.Document.head.eval') Until IsObj($jsEval) ; if jQuery is not already loaded then load it If $jsEval("typeof jQuery=='undefined'") Then ; check if the '$' (dollar) name is already in use by other library If $jsEval("typeof $=='function'") Then $otherlib = True Local $oScript = $oIE.document.createElement('script'); $oScript.type = 'text/javascript' ; If you want to load jQuery from a disk file use the following statement ; where i.e. jquery-1.9.1.js is the file containing the jQuery source ; (or also use a string variable containing the whole jQuery listing) ;~ $oScript.TextContent = FileRead(@ScriptDir & "\jquery-1.9.1.js") ; <--- from a file ; If you want to download jQuery from the web use this statement $oScript.src = 'https://code.jquery.com/jquery-latest.min.js' ; <--- from an url $oIE.document.getElementsByTagName('head').item(0).appendChild($oScript) Do Sleep(250) Until $jsEval("typeof jQuery == 'function'") EndIf Do Sleep(250) $jQuery = $jsEval("jQuery") Until IsObj($jQuery) If $otherlib Then $jsEval('jQuery.noConflict();') Return $jQuery EndFunc ;==>_jQuerify  
×