JavaScript/Jsoup - Get background-image url from "i class" - javascript

So I'm loading a webpage in my app's webview and there's an HTML i class="img profimage" and it has a background-image url and that's my target...
I want to get that target either with JavaScript or using Jsoup...
What I tried so far with Jsoup is this:
public class GetImage extends AsyncTask<String, String, String> {
protected String doInBackground(String... strings) {
Document document = null;
try {
document = Jsoup.connect(url).get();
} catch (IOException e) {
e.printStackTrace();
}
String temp = document.select("i.img.profpic").first().getElementsByAttribute("style").toString();
return temp.substring(temp.indexOf("(") + 1, temp.indexOf(")"));
}
 
protected void onPostExecute(String result) {
Log.d("ChatScreen", result);
Toast.makeText(ChatScreen.this, result, LENGTH_SHORT).show();
}
}
But I'm getting NPE...
I don't know how to get background-image url of an i class using JavaScript... I can find plenty of examples on web for how to get it for div using ids
HTML structure of page is similar to this:
<div ....>
<div ....>
<i class="img profimage" style="background-image: url("url here");"/>
</div>
</div>

Check this Answer may be this will work but I didn't try this. The JS function is written bellow in evaluateJavascript() which will read style attribute then you can use substring method to get the URL.
webview.evaluateJavascript(
"(function() { return (document.getElementsByTagName('i')[index].getAttribute('style')); })();",
new ValueCallback<String>() {
#Override
public void onReceiveValue(String html) {
Log.d("HTML", html);
// now use substring to get url.....
}
});
Hope this help you.

Referencing this answer, you could try something like below (assuming it's the only/first element with the class profimage, otherwise change the index, i.e. [n], where n is the index). Alternatively, just give the element a unique id and use document.getElementById('imgid') and remove the [0]. Wrapped it in a function in case you want to call it on a specific event.
function getUrl() {
var img = document.getElementsByClass('profimage'),
style = img[0].currentStyle || window.getComputedStyle(img[0], false),
bi = style.backgroundImage.slice(5, -2);
return bi;
}
Slicing will remove url(" before and ") after the URL itself. Note that this returns the full url.
If that doesn't work, you can try style = img.style, in lieu of the longer expression in the code above, since the background image is added with inline css in the element itself (<i ... style="background-image: url("url here");"/>). This will return the url in the inline style, in this case url here.

Related

Javascript click event not working in Blazor client side app

I'm new to Blazor and I've created a pretty simple Webassembly app. I want a href link to go to a div lower down the page when I click on it, but the Javascript click event won't work. In the Index.razor page the JsRuntime.InvokeVoidAsync("clicker") is working and the alert("In clicker") happens as the page loads, but the click / href to go the "intro" div will not work for love nor money :-/
index.html
<!DOCTYPE html>
<html>
<head>
<title>My Blazor App</title>
<!--script type='text/javascript' src='./scripts/app.js'-->
</head>
<body>
<app>Loading...</app>
<script src="_framework/blazor.webassembly.js"></script>
<script>
function clicker() {
alert("In clicker"); // this works
document.getElementById('skip').onclick = function(e){
alert("clicked"); // this works but the page still won't scroll to the "intro" div :(
}
}
//clicker();
</script>
</body>
</html>
Index.razor (#code section is at top of page)
#page "/"
#code {
[Inject]
protected IJSRuntime JsRuntime { get; set; }
protected override void OnAfterRender(bool firstRender)
{
if (firstRender)
{
JsRuntime.InvokeVoidAsync("clicker");
}
}
}
// This link won't go to the intro div when clicked :(
<a id="skip" class="skip" href="#intro">skip this bit</a>
...
<div id="intro" class="home">
...
</div>
Startup.cs
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IComponentsApplicationBuilder app)
{
app.AddComponent<App>("app");
}
}
If anyone could shed some light on this it would save my week.
There is no need for JavaScript here.
If you add a specific target to your markup, it will just work.
You can use target="_top" to avoid Blazor navigation interception.
<a class="skip" href="#intro" target="_top">skip this bit</a>
...
<div id="intro" class="home">
...
</div>
Note that target="_top" just directs the browser to navigate within the topmost frame in the window, it does not mean you will scroll to the top!
The page won’t scroll to the element you’ve specified in the link.This has to do with how routing is handled in Blazor and most other SPA applications as well. A simple solution is that you could create your own AnchorLink component and use a little bit of JavaScript interop magic.
1.Create AnchorLink.razor in Pages/Shared
#code {
public AnchorLink()
{
this.Attributes = new Dictionary<string, object>();
}
private string targetId = null;
private bool preventDefault = false;
/// <summary>
/// This parameter supports arbitrary attributes.
/// </summary>
/// <remarks>
/// Any attribute specified on the component, which is not defined as a parameter, whill be added to this dictionary.
/// It is then uses as the source for attributes rendered onto the resulting HTML element below in the markup section
/// of this component.
/// For details, refer to <see cref="https://learn.microsoft.com/en-us/aspnet/core/blazor/components#attribute-splatting-and-arbitrary-parameters"/>.
/// </remarks>
[Parameter(CaptureUnmatchedValues = true)]
public IDictionary<string, object> Attributes { get; set; }
/// <summary>
/// Supports child content for the component.
/// </summary>
/// <see cref="https://learn.microsoft.com/en-us/aspnet/core/blazor/components#child-content"/>
[Parameter]
public RenderFragment ChildContent { get; set; }
[Inject]
protected IJSRuntime JsInterop { get; set; }
protected override void OnParametersSet()
{
string href = null;
if (this.Attributes.ContainsKey("href"))
{
// If the href attribute has been specified, we examine the value of it. If if starts with '#'
// we assume the rest of the value contains the ID of the element the link points to.
href = $"{this.Attributes["href"]}";
if (href.StartsWith("#"))
{
// If the href contains an anchor link we don't want the default click action to occur, but
// rather take care of the click in our own method.
this.targetId = href.Substring(1);
this.preventDefault = true;
}
}
base.OnParametersSet();
}
private async Task AnchorOnClickAsync()
{
if (!string.IsNullOrEmpty(this.targetId))
{
// If the target ID has been specified, we know this is an anchor link that we need to scroll
// to, so we call the JavaScript method to take care of this for us.
await this.JsInterop.InvokeVoidAsync("anchorLink.scrollIntoView", this.targetId);
}
}
}
<a href="" #onclick="this.AnchorOnClickAsync" #onclick:stopPropagation="false" />
<a #attributes="this.Attributes" #onclick="this.AnchorOnClickAsync" #onclick:preventDefault="this.preventDefault">Hello #this.ChildContent</a>
2.Add js in wwwroot/Index.html
<script src="_framework/blazor.webassembly.js"></script>
<script>
window.anchorLink = {
scrollIntoView: function (elementId) {
// This function is called from the AnchorLink component using JavaScript interop.
// It will try to find an element using the ID given to the function, and scroll that
// element into view, if an element is found.
var elem = document.getElementById(elementId);
if (elem) {
elem.scrollIntoView();
window.location.hash = elementId;
}
}
}
</script>
3.Index.razor
<AnchorLink class="skip" href="#intro">skip this bit</AnchorLink>
Refer to https://mikaberglund.com/2019/12/28/creating-anchor-links-in-blazor-applications/

Better way of manipulating the DOM in Angular2

What's the better way of manipulating the DOM to change the background of a specific div, rather than using document.getElementById('id').style.backgroundImage.
I'm trying to change backgrounds as I change my Url, but the only way I could think and easy is using document.getElementById()
changeBg() {
var urlPath = window.location.pathname.split('/');
switch (urlPath[4]) {
case "Refreshments%20North":
document.getElementById('homeBg').style.backgroundImage = "url('./assets/imgs/spur-2.jpg')";
break;
... more cases
default:
document.getElementById('homeBg').style.backgroundImage = "url('./assets/imgs/background.jpg')";
}
}
I also tried Renderer dependency but how do I target homeBg using this?
this.renderer.setElementStyle(this.elRef.nativeElement, 'background-image', "url(./assets/imgs/spur-2.jpg)");
Template -- is basically just a div
<nav></nav>
<div id="homeBg"></div>
Edit --
Moved my changeBg() to my sharedService
public changeBg() {
var urlPath = window.location.pathname.split('/');
switch (urlPath[4]) {
case "Refreshments%20North":
this.homeBg = this.sanitizer.bypassSecurityTrustStyle("url('./assets/imgs/spur-2.jpg')");
break;
default:
this.homeBg = this.sanitizer.bypassSecurityTrustStyle("url('./assets/imgs/background.jpg')");
}
}
Calling changeBg() service in my profile component
ngOnInit() {
this.sharedService.changeBg(); // is this correct?
}
Profile template -- like this gives me an error Cannot read property 'homeBg' of undefined
<div class="home" id="homeBg" [style.background-image]="changeBg?.homeBg"></div>
Change background with route.param.subscribe()
this.routeSub = this.route.params.subscribe(params => {
this.sharedService.changeBg();
}
Using binding and directives is the preferred way in Angular2 instead of imperative DOM manipulation:
<div [style.background-image]="myService.homeBg"
You need to sanitize the URL for Angular to accept it.
See In RC.1 some styles can't be added using binding syntax for more details.
changeBg() {
var urlPath = window.location.pathname.split('/');
switch (urlPath[4]) {
case "Refreshments%20North":
this.homeBg = this.sanitizer.bypassSecurityTrustStyle("url('./assets/imgs/spur-2.jpg')");
break;
... more cases
default:
this.homeBg = this.sanitizer.bypassSecurityTrustStyle( "url('./assets/imgs/background.jpg')");
}
}
See also How to add background-image using ngStyle (angular2)?
You can use template references and #ViewChild decorator:
template :
<div #myDiv id="homeBg"></div>
component :
class MyComponent implements AfterViewInit{
#ViewChild("myDiv")
elRef:ElementRef
ngAfterViewInit(){
this.renderer.setElementStyle(this.elRef.nativeElement, 'background-image', "url(./assets/imgs/spur-2.jpg)");
}
}

Detect parents' and grandparents' links in Javascript

I am making a Web Browser in C# and displaying custom context menus based on the element right clicked by the user. I am having trouble figuring out which elements should be treated as links?
if (el_tag == "a")
showLinkMenu();
else if (el_tag == "img" && parent_tag == "a")
showAdvancedMenu();
else if (el_tag == "img")
showImgMenu();
Shot1: Google chrome detected this as a link
Shot2: Structure a > div > div > div > div > img
What should I do to detect such links?
You should iterate up the list of parent tags and call it a link if any of them are an <a> with an href attribute.
I recommend implementing your own IContextMenuHandler and use the built in CefMenuCommand's and TypeFlag's to help you. With this, you can add or remove context menu items based on the element that has been right-clicked.
MenuHandler.cs
internal class MenuHandler : IContextMenuHandler
{
private const int SaveImage = 26503;
private const int OpenLinkNewTab = 26501;
public event EventHandler OnSaveImage = delegate { };
void IContextMenuHandler.OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
{
if(parameters.TypeFlags.HasFlag(ContextMenuType.Media) && parameters.HasImageContents)
{
model.AddItem((CefMenuCommand)SaveImage, "Save image");
}
if(!string.IsNullOrEmpty(parameters.UnfilteredLinkUrl))
{
model.AddItem((CefMenuCommand)OpenLinkNewTab, "Open link in new tab");
}
}
bool IContextMenuHandler.OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
{
return false;
}
void IContextMenuHandler.OnContextMenuDismissed(IWebBrowser browserControl, IBrowser browser, IFrame frame)
{
if ((int)commandId == SaveImage)
{
OnSaveImage?.Invoke(this, new ImageSaveEventArgs(parameters.SourceUrl)); //ImageSaveEventArgs is just a class with one property that houses the source url of the image to download.
}
}
bool IContextMenuHandler.RunContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback)
{
return false;
}
}
Then wherever you create your ChromiumWebBrowser instance, you can do something like this:
ChromiumWebBrowser browser = new ChromiumWebBrowser();
MenuHandler menuHandler = new MenuHandler();
menuHandler.OnSaveImage += Handler_OnSaveImage;
browser.MenuHandler = menuHandler;
private void Handler_OnSaveImage(object sender, EventArgs e)
{
DownloadImage(((ImageSaveEventArgs)e).SourceUrl);
}
Note, this is just an example of using the built-in IContextMenuHandler to obtain what the user has right-clicked, and then handling my own event so I can implemented the required behaviour. In this case, the ability to download a file from the URL.
See MenuHandler.cs on CefSharp's GitHub page for more details and other examples.

Awesomium .NET. Wpf. TitleChanged event

I have a very basic application, that shows website content within the WPF app. Everything works fine, except TitleChangedEvent. Here is the code sample (XAML):
<Window xmlns:awe="http://schemas.awesomium.com/winfx" x:Class="ShopChat.Desktop.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:webControls="clr-namespace:System.Web.UI.WebControls;assembly=System.Web"
Title="{Binding ElementName=WebControl, Path=Title}" MinHeight="480" MinWidth="640">
<Grid>
<awe:WebControl x:Name="WebControl"/>
</Grid>
And this is main window code-behind:
public MainWindow()
{
InitializeComponent();
string url = #"http://shopchat.dev";
try
{
url = ConfigurationManager.AppSettings.Get("Url");
}
catch (Exception)
{
}
WebControl.Source = new Uri(url);
WebControl.TitleChanged += WebControl_OnTitleChanged;
this.WindowTitle = "Quickchat";
}
public string WindowTitle
{
get { return (string)GetValue(WindowTitleProperty); }
set { SetValue(WindowTitleProperty, value); }
}
// Using a DependencyProperty as the backing store for WindowTitle. This enables animation, styling, binding, etc...
public static readonly DependencyProperty WindowTitleProperty =
DependencyProperty.Register("WindowTitle", typeof(string), typeof(MainWindow), new PropertyMetadata(null));
private void WebControl_OnTitleChanged(object sender, TitleChangedEventArgs e)
{
this.WindowTitle = e.Title;
}
I've also tried to bind to window title directly using Binding ElementName=WebControl. That didn't help me either.
JavaScript client code is very simple: it changes the document title on timer (setInterval).
What am I doing wrong?
try like this code
public MainWindow()
{
InitializeComponent();
DataContext = this;
MyTitle = "Title";
}
Then you just need in the XAML
Title="{Binding MyTitle}"
Then you don't need the dependency property.
Then I would like to use this INotifyPropertyChanged with a standard property.
The issue was solved. TitleChanged event seemed to be insufficient. I've incorporated the usage of global js object to get the necessary behavior.

How to catch element click by ID in Android webview?

I have the viewPager component which is containing the several webviews with HTML content from remote server.
Is it simple HTML code without possibility to change the HTMl output on the server side.
I would like to ask, how can i catch the click(tap) event on the specified element with the given ID in Android?
ViewPager
private void initViewPager() {
pager = (ViewPager) findViewById(R.id.my_pager);
adapter = new FragmentStatePagerAdapter(
getSupportFragmentManager()
) {
#Override
public int getCount() {
// This makes sure getItem doesn't use a position
// that is out of bounds of our array of URLs
Logger.d(String.valueOf(mWelcomeController.loadedPagesToDisplay.size()));
return mWelcomeController.loadedPagesToDisplay.size();
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
Logger.d(mWelcomeController.loadedPagesToDisplay.toString());
return BrowserFragment.newInstance(
mWelcomeController.loadedPagesToDisplay.get(position)
);
}
};
//Let the pager know which adapter it is supposed to use
pager.setAdapter(adapter);
}
Because I cannot modify the HTML output on the server side (maybe inject some attributes into DOM on device ?) I cannot use something like that:
http://www.scriptscoop.com/t/21b53b896c9e/javascript-how-to-detect-button-click-in-webview-android.html
Detect click on HTML button through javascript in Android WebView.
I would like just something like this:
Find the given element in the HTML code
Update the HTML code (add
onclick event)
Catch this event in native code
For that you need to parse the html, a good html parser for Java (and therefor also Android) is Jsoup.
You can do something like:
// Connect to the web site
Document doc = Jsoup.connect(url).get();
Element button = doc.select("#buttonid");
button.html("new stuff here");
//parse back and put in webview
String finaloutput = doc.html();
1.
// setting
wv.addJavascriptInterface(new MyJsToAndroid(),"my");
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
2.
// JsCallBack
class MyJsToAndroid extends Object{
#JavascriptInterface
public void myClick(String idOrClass) {
Log.d(TAG, "myClick-> " + idOrClass);
}
}
3.
// JS--
public static String addMyClickCallBackJs() {
String js = "javascript:";
js += "function myClick(event){" +
"if(event.target.className == null){my.myClick(event.target.id)}" +
"else{my.myClick(event.target.className)}}";
js += "document.addEventListener(\"click\",myClick,true);";
return js;
}
4.
#Override
public void onPageFinished(WebView wv, String url) {
//...
wv.evaluateJavascript(addMyClickCallBackJs(),null);
//...
}
So, look at the 2 log.

Categories

Resources