w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
$x() function is not defined inside a Chrome extension, content script
$x() is not part of the run-time environment of a web page or content script. It is a tool that is part of the Command Line API for Chrome's DevTools. To use XPath in a content script, you need to do it the normal way, the DevTools convenient shortcut is not available. Your code would look like this: var jpgLinks = document.evaluate ( "//a[contains(@href,'.jpg')]", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null ); var numLinks = jpgLinks.snapshotLength; for (var J = 0; J < numLinks; ++J) { var thisLink = jpgLinks.snapshotItem (J); console.log ("Link ", J, " = ", thisLink); } -- which is the kind of thing that $x() was doing for you, behind the scenes. While you are at it, consider switching to CSS selectors. Then the same funct

Categories : Javascript

detect if Chrome extension content script has been injected / content script include guard
Implementing an include guard is extremely easy: (function() { if (window.hasRun) return; window.hasRun = true; // Rest of code })(); If you want to programatically inject a content script, consider using one of the webNavigation events (e.g. onCommitted) instead of chrome.tabs.onUpdated. Unlike the tabs events, the webNavigation events are also triggered for navigation within frames, and offer a way to declare an URL filter in advance.

Categories : Javascript

How to inject content script inside an html page which runs within an extension
Chrome extensions can't inject content scripts into Chrome extensions. You'll want to use message passing instead.

Categories : Google Chrome

Chrome extension: can't get message passing to work between background script and content script
From onMessage documentation. This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called). So your code should look like chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension"); if (request.greeting == "hello") { sendResponse({farewell: "goodbye"}); return true; } });

Categories : Javascript

Remote script as content script in Chrome extension
$.getScript defaults to injecting a <script> element to load scripts from a different origin. Consequently, the code runs in the context of the page, not the content script (see also). If you really want to use jQuery to get the script, replace $.getScript("https://mysite.com/myremotescript.js", function(){ }); with the following (eval is used as a callback, thus it evaluates the response of the request) $.get("https://mysite.com/myremotescript.js", eval); While this works, I recommend to cache the script's response body. Then, your extension will not break if the network connection drops. And, more importantly, the user will not get a useless request for every page load. I've fleshed out this concept before, see this answer.

Categories : Jquery

Chrome Extension: How to a call a function defined in content script?
Well, I just added the content of my function in the head of DOM and then called it. var head = document.getElementsByTagName("head")[0]; fn = "function closepop(){alert('jj');}"; var script = document.createElement('script'); script.setAttribute("type", "application/javascript"); script.textContent = fn; head.appendChild(script); Is there any cleaner way to do it?

Categories : Javascript

Script fails to access the content in inside tag
The for loop is iterating over all product elements and calling clear() on them, which removes all text and subelements. Since you're printing on the end event of the outer product elements, you are removing the text for the inner product elements before you print.

Categories : Python

How to run a script that it has to connect 3 solaris servers, do some operations and create files in the machine where the script is running?
Use sshfs to mount the needed directories of your three servers. Afterwards you can run the script locally accessing the remote data as local files.

Categories : Bash

How do you detect that a script was loaded *and* executed in a chrome extension?
I'm not familiar with Chrome Extensions (only browser javascript), but I think that you will unfortunately have to edit your loaded JS so that is calls a function of your choice when it is executed, if you want to do this nicely. This it what Google does for asynchronously loading its Maps Javascript file: function loadScript() { var script = document.createElement("script"); script.type = "text/javascript"; script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=executed"; document.body.appendChild(script); } function executed() { /* Google maps has finished loading, do awesome things ! */ } If you really don't want to edit your loaded JS files, you could have a setInterval (or a recursive function with setTimeout) checking regularly if some functions

Categories : Google Chrome

How to allow cross domain content script on Firefox add-on without firing mixed content blocking errors
Specifying that permission will cause the Sandbox (worker in SDK internal terms, content script in documentation) to simply get a new XMLHttpRequest constructor, that has more than one principal (or "origin", if you like). This will only change how to same-origin-policy is evaluated, but not how security in general and mixed-content policies in particular are implemented. That is: You still cannot do a https to http XHR, as you noticed. There is no work around you can use in your content script. You could however message your main script to do the request and pass the result back (again via message passing) to the content script. Please file a bug. At the very least this limitation should be documented. Personally, I wouldn't be in favor of lifting it. Mixed-content is a security issue,

Categories : Javascript

How can I make my content script run only in the tab that the extension is in?
Its not directly possible because an extension loads a content script based on url not tabs, due to security policies. You can try this: Create a background script and define a function which determines whether you want the content script to load in a specified tab or not (use tab id to identify tabs). Create a content script that loads on all urls (call it loader.js). From it call the background script function (Use chrome.runtime.sendMessage to communicate with background script) to determine load your main script or not. If its a positive you can proceed with loading your main content script from loader.js.

Categories : Google Chrome

How should I handle Chrome tabs that don't yet have a content script loaded?
In the end I couldn't do it with connect, I had to use the one shot sendMessage() which has a call-back function when the response comes in. That can then be interrogated for success and the state of lastError. The code now looks like this: // Called when the user clicks on the browser action. // // When clicked we send a message to the current active tab's // content script. It will then use heuristics to decide which text // area to spawn an edit request for. chrome.browserAction.onClicked.addListener(function(tab) { var find_msg = { msg: "find_edit" }; // sometimes there is no content script to talk to which we need to detect console.log("sending find_edit message"); chrome.tabs.sendMessage(tab.id, find_msg, function(response) { console.log("sendMess

Categories : Javascript

Make script affect on dynamic loaded content
Use on and delegate to an element that is present when the page loads. For example, if the dynamically created div that is not present on page load looks like this <div id="dynamic"></div> Your JS would look like this $(body).on(event, '#dynamic', function(){ Script }); Where event is equal to click, mousedown, etc.

Categories : Jquery

Firefox add-on sdk : how to use simple-storage API in a content script?
tabs.activeTab.attach (...) returns a worker with which you can use to sent messages between the content script and the addon. With this you can have the content script send messages to the addon about what data to store in simple-storage. So the addon side would look like: let worker = tabs.activeTab.attach(...); worker.port.on('simple-storage', function(newData) { ss.storage = newData; }); and the content script side would look like: self.port.emit('simple-storage', newData) when you have newData to save.

Categories : Javascript

jquery load content into script tag in firefox
You are using the type as this <script id="navigation-template" type="text/x-handlebars-template"></script> Try changing the type to <script id="navigation-template" type="text/javascript"></script>

Categories : Javascript

Why doesn't a console loaded script have access to the DOM?
Here is a working solution to add JQuery: var jq = document.createElement('script'); jq.src = "//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"; document.getElementsByTagName('head')[0].appendChild(jq); jQuery.noConflict();

Categories : Javascript

Chrome Extension: How to remove content script after injection?
No. You can't "remove" it. Running a content script can have side effects, like declaring variables and functions on the window object, connecting to the background page, or listening to DOM events. If your content script has no side effects, it is identical to not being injected at all. If you want to re-inject it, simply call executeScript with either a code or source parameter. It can be nice to simply define your injected scripts as functions, then calling .toString() on the functions, and injecting them as raw strings with the "code" argument to executeScript. Arguments to these functions can be inserted as JSON strings, which is even more convenient.

Categories : Javascript

Communicating between Chrome DevTools and content script in extension
As pointed out by Alex, here's a typo in your code which prevents it from working. Drop your current code and use chrome.devtools.inspectedWindow.eval to directly run the code and parse the results. This simplifies your complicated logic to: devtools creates a panel where the user writes code devtools runs code devtools handles result PS. There is a way to manipulate the existing console, but I recommend against using it, unless it's for personal use. Two different ways to do this are shown in this answer.

Categories : Javascript

Chrome extension: Eliminate CSS inheritance for content script
I recently created Boundary, a CSS+JS library to solve problems just like this. Boundary creates elements that are completely separate from the existing webpage's CSS. Take creating a dialog for example. After installing Boundary, you can do this in your content script var dialog = Boundary.createBox("yourDialogID", "yourDialogClassName"); Boundary.loadBoxCSS("#yourDialogID", "style-for-elems-in-dialog.css"); Boundary.appendToBox( "#yourDialogID", "<button id='submit_button'>submit</button>" ); Boundary.find("#submit_button").click(function() { // find() function returns a regular jQuery DOM element // so you can do whatever you want with it. // some js after button is clicked. }); Elements within #yourDialogID will not be affected by the existing webpage.

Categories : CSS

Message Passing between Chrome Extension and Content Script
If you check the injected page's console, you should see something like TypeError: Converting circular structure to JSON This is because you are trying to pass an HTML object through JSON. Try passing just the ID of the button instead and see if it works then.

Categories : Google Chrome

unable to access variable declared in ksh script to csh script using shell script
The ksh script is not doing what you think it is doing when used by ksh; it sets $1 first to MyUser=root and then MyPassword=shroot. However, when you source it from your C shell script, because the syntax is compatible with C shell (checked with tcsh), you would set the two variables. If you sourced the script from a Bourne-shell derivative, the exit at the end of the ksh script would cause the shell to exit; it does not seem to cause the C shell to exit. So, what you've got is a weird hybrid. Normally, you stick to one language and use it exclusively. Where you need to use another shell, you can do so, but you simply run the script written for the other shell. You can communicate to the other script with environment variables. You don't normally try writing sourceable code that ca

Categories : Shell

Chrome Extension's Content Script catch custom events?
Yes, content script can communicate with the injected web page. Because the context of content script and injected web page are isolated from each other, they must communicate with shared DOM. I think content script can't catch the custom event which was fired by injected page directly. But you can post message to content script when specific custom event is fired. window.postMessage can fit your needs. Injected page: <!DOCTYPE html> <html> <head> <title></title> </head> <body> <button id="btn">test</button> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> $("#btn").click(function(){ $(document).trigger("MY_EVENT"); }); $

Categories : Javascript

Triggering a click event from content script - chrome extension
jQuery's click trigger function does not trigger a non-jQuery DOM click listener (jsfiddle.net/k2W6M). The jQuery documentation should really point out this fact. I'm sure more than a few people have gone on a wild chase over this. I was struggling with this same problem for a few days, trying to trigger an onclick handler on a link with .click() and .trigger("click"), all in vain, until I saw this. For the sake of having a complete answer to this question, dispatching a MouseEvent to the element has the same effect as clicking the element. The following code worked for me, and should work when trying to click an element/link on a page from a content script: $(css_selector)[0].dispatchEvent(new MouseEvent("click"))

Categories : Javascript

How to run script when page loads content dynamically for Chrome Extension
You can use MutationObserver to do this. Check documentation here. Example of usage and fiddle available in this SO question.

Categories : Javascript

How javascript function are loaded in the script tag
1.Are these functions retrieved from js files or any other mechanism? No, built-in functions are part of the language and most likely implemented in C or C++. However, since JavaScript is a dynamic language, a built in function could be re-defined somewhere by a Javascript function. For example: String.prototype.substr = function () { return 'Take that, built-in function!'; }; var s = 'Hello'; window.alert(s.substr(1,2)); 2.If yes where are they located? See answer 1. However, with open-source JavaScript engines you'd be able to dig up the source code online if you were curious about the implementation of these built in functions. For example, the source code to V8, the JavaScript engine Chrome uses, can be found here. One way to tell if a function is native would be to p

Categories : Javascript

How to access page variables from Chrome extension background script
Nope. That's not possible. You may inject a script, but it only have an access to DOM and it could make DOM manipulations. It can not read javascript variables or execute functions in the context of the current page. Your javascript code is run in a sandbox and you are restricted only to the DOM elements.

Categories : Javascript

Chrome extension : error when sending message back from injected script to background script
I think my issue was fixed by chrome.tabs.sendMessage(tabId, {action: 'test'}, Note, I incorrectly use msg instead of action in above question. Also, I do not use the third parameter sendResponse to avoid full-duplex communication I simply post another message from content script back to background page. From content script, send message to background page using: function SendMessageToBackgroundPage(data) { chrome.runtime.sendMessage({ action: 'kungfu', source: 'panda' }); } Catch it inside background page using: chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { switch (request.action) { case 'kungfu': alert(request.source); } });

Categories : Javascript

Windows batch script - How to filter files with defined extension
You might try this: set "AllowExt=.jpg .png .bmp" for %%a in (%AllowExt%) do ( forfiles /p D:Pictures /m *%%a /c "cmd /c echo @file" ) "cmd /c echo @file" is the default command, see forfiles /?.

Categories : Windows

error with global name when running a script from another script - python
This is a pretty interesting problem. First a quick workaround, you can provide dictionaries to use as the local and global namespace when calling execfile(), using an empty dictionary for globals works fine: # test_fun1.py a = 1 def test1(): print a execfile('test_fun2.py', {}) test1() Alternatively, if you want the code to execute within the global scope of your module you can use globals() instead of {}. Now on to why this isn't working... from the documentation on execfile(): If both dictionaries are omitted, the expression is executed in the environment where execfile() is called. Here "both dictionaries" is referring to the optional globals and locals arguments to execfile(). In this case "the environment where execfile() is called" is the local scope of the fun

Categories : Python

How run a Python script from another script and get resulting global dict?
Importing a module executes the code at the top level, and that module's "global" namespace gets imported as the name of the module james@bodacious:~$cat test.py def func(): pass myname = "michael caine" print "hello, %s" % myname james@bodacious:~$python Python 2.7.5 (default, Jul 12 2013, 18:42:21) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import test hello, michael caine >>> dir(test) ['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'func', 'myname'] >>> if the code you want to be run is at the top level of the file, just importing the module will execute the code and give you access to its "global" namespace all in one convenient package.

Categories : Python

Content Security Policy: If set, cannot load script from bookmarklet. Is a browser extension granted clearance?
Oh I just needed to read a little further (oh Github, you're awesome): https://github.com/blog/1477-content-security-policy The answer is yes! User configured scripts should always be granted clearance! (but we are off to a rocky start it seems) I actually think there's significant opportunity for social engineering happening here; "Install this bookmark in your browser to use our cute emoticons in forums!" "oh bookmarks can't be viruses, right?"

Categories : Google Chrome

Chrome Extension: content script is unable to load local HTML file into iframe
You need to set the file in the web_accessible_resources and it is case sensitive.

Categories : Javascript

how can global function expression can access variable inside containing function in javascript
You can't access the property x declared in the closure from outside. Here, you don't read the value of the private variable x, but the copy you made and stored into a. If your question is why you could access x from inside the function Obj : that's simply how closures work : a function can access the variables of the scope in which it was declared. The fact that this function is assigned to the Obj variable and that this variable is global changes absolutely nothing. Here's some additional reading : the MDN on closures

Categories : Javascript

Is there an easy way to tell if an R script made use of any function in a loaded package?
Try this: 1) First issue a library() call for each package that you do NOT want to test for. In this case there is only one package which is the one we wish to test for so we can skip this step. 2) Run the script with library dummied out: library <- list source("script.A") rm(library) # restore If you get no errors then the script does not depend on the package.

Categories : R

How to load a java script function when the webpage completely gets loaded?
Its very important what your requirement is here. Is it early enough for you to do something when the DOM is "ready" (which pretty much means, accessible via ECMAscript) or do you need to wait for all kind of resources to be completely and entirely loaded ? If it is the former, the DOMContentLoaded event is your choice. For the latter case, the window load event will make you happy. Using jQuery, this is either $( document ).ready(function() { // do stuff when the DOM is ready }); or $( window ).load(function() { // do stuff when all resources (images, iframes, ...) were loaded }); If there are any asyncronous processes involved by any 3rd party script-loader, you have no choice but to get into any kind of callback mechanism, which should be provided by those scripts.

Categories : Javascript

How to create a bash script that will lower case all files in the current folder, then search/replace in all files?
Something like this should work: #!/bin/bash for file in *.html do lowercase=`echo $file | tr '[A-Z]' '[a-z]'` mv "$file" "$lowercase" for f in *.html do sed -i "s/$file/$lowercase/g" "$f" done done Change *.html to *.<extension> if you're working with something other than html files.

Categories : Bash

Refused to load the script because it violates the following Content Security Policy directive: "script-src 'self'
If you build a packaged app, you can not load external script. Your application must embed every scripts, styles or images. Check this link to ensure you are following chrome app CSP rules: https://developer.chrome.com/extensions/contentSecurityPolicy

Categories : Google Chrome

No inlined script, still getting "Refused due to Content Security Policy directive: "script-src 'self'"
I had indeed messed things up a bit, although the reasons were a bit unclear. Turns out the culprit was "BANNER ". Chrome defines the javascript:void(0) call as an inlined script call. Switching the href to '#' removed the error message. The reason no tab was being opened was that attempts were made to add behaviour to components being created asynchronously in the (ajax) method getJSON(), which had not yet finished at that point. A quick move of the loop solved the issue, and things now work as expected.

Categories : Javascript

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'"
I also faced such type of problem when working with LinkedIn oAuth API. I was using linkedIn API with following settings for cordova config.xml <access origin="*" launch-external="yes"/> <allow-navigation href="*" /> Meta Tag was <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"> Script <script type="text/javascript" src="http://platform.linkedin.com/in.js"></script> When i run the application on emulator its giving Fixed Problem to add uri into meta tag http://platform.linkedin.com like <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' http:

Categories : Google Chrome

sendMessage from background script to content script in app fails
There's not such a thing called "Content scripts" in a Chrome app. Your manifest file looks like a mixture of a Chrome extension. Open chrome://extensions/, enable developer mode, and you would see a warning that the "background" and "tabs" permissions are invalid for a Chrome app. If you're implementing a Chrome app, just use chrome.runtime.sendMessage and chrome.runtime.onMessage. These messages can be send from and to your event page and the main page. For example: // event page (aka background page) chrome.app.runtime.onLaunched.addListener(function() { chrome.app.window.create('main.html'); }); // Later, when you want to notify the app window chrome.runtime.sendMessage(" ... any message ... "); <!-- main.html --> <script src="main.js"></script> //

Categories : Google Chrome



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.