How to change WebView's webpage position? OSX - objective-c

Let's say I have a WebView that loads up twitter.com.
Here's what appears in my WebView:
And here's what I want to show:
How can I change the default Upper Left Corner position of website on the WebView to display another position of the same website?

I get it to move using this (you need to set the frameLoadDelegate):
-(void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
{
if (frame == self.myWebview.mainFrame)
{
DOMDocument *mainDoc = [self.myWebview.mainFrame DOMDocument];
DOMNodeList *list = [mainDoc getElementsByClassName:#"front-signin js-front-signin"];
DOMNode *loginElement = [list item:0];
NSRect myRect = loginElement.boundingBox;
[self.myWebview stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"window.scrollTo(%d,%d);", (int)myRect.origin.x, (int)myRect.origin.y]];
}
}
"front-signin js-front-signin" being the name of the class used in the source html of www.twitter.com.
So it is failure prone to rely on that which could change at any time.
There is also in this case the header that doesn't move. So either account for it and display it, or move your view up the size of this header and hide it.
You need to adjust the scrollTo call to center it in your view.
And you might want to consider fading the view once it's loaded, cause the scroll is kind of jerky, and not very osx like.
But apart from this, it could work ;-)

You could execute javascript in the UIWebView:
[webView stringByEvaluatingJavaScriptFromString:#"window.pageYOffset=200;"];
This should scroll the window down 200 pixels.

You can use the following on OS X:
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:#"window.scrollTo(%f, %f)", xPos, yPos]];

You can also play with the webview's scrollView contentOffset.
UIWebView * webView = [[UIwebView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.twitter.com"]]];
[webView.scrollView setContentOffset:CGPointMake(50, 60)];
[webView release];

Related

UIWebView not full screen on rotate

(This looks like a question that has been asked/answered 100 times but I can't get it to work.)
I have a view controller that is story board based. Nested in the main view is a webUIView.
In the controller method viewDidLoad I am simply specifying the URL and setting the view and the webUIView to autoresize:
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:#"index" ofType:#"html" inDirectory:#"web_app_build"]];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
[_browser loadRequest:request];
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
self.view.autoresizesSubviews = TRUE;
self.browser.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
I also added this method
-(void)viewWillLayoutSubviews {
[super viewWillLayoutSubviews];
self.browser.frame = self.view.bounds;
}
When I rotate the device the webUIView rotates, but doesn't resize to fill the screen. I did try writing my own rotation handler but this seems the entirely wrong way to do that.
I did read the apple doc on the topic. How can I make the webUIview resize to fit the display size on rotate?
The issue you're having is that self.view.bounds has most likely not been adjusted yet to the bounds after rotation. Set a breakpoint to check this out. I would move the code to viewDidLayoutSubviews: instead. If you don't need to support versions of iOS before iOS 6, I'd strongly recommend looking into using Auto Layout for your view objects. It will make your life a lot easier.

Added whitespace in UIWebview - removing UIWebView whitespace in iOS7 & iOS8

Im loading local html files, since iOS7 there is added white space on top in the UIWebView.(I cant post an image as i do not have enough points.)
image can be seen here- snap shot from iPhone simulator, uiwebview surrounded by black frame, the html content is grey, but there is white added above it
I have tried to adjust the zoom using
[webView stringByEvaluatingJavaScriptFromString:#"document. body.style.zoom = 5.0;"];
webView.scalesPageToFit = NO;
credit to: Srikar Appal
I also set tried to remove white spacing:
NSString *padding = #"document.body.style.margin='0';document.body.style.padding = '0'";
[webView stringByEvaluatingJavaScriptFromString:padding];
credit to: thenextmillionaire
still no luck. In the desktop chrome browser there is no whitespace. The html files are Google Swiffy files - containing html and JSON.
edit: updated Image
Try self.automaticallyAdjustsScrollViewInsets = NO; in ViewDidLoad.
ios 7 add 64px automatically for scroll view. (status bar and nav bar)
This problem only affects the UIWebView if it is the first subview of the parent view. One alternative way to work around this problem is to add another non-visible empty view to the parent view as the first view. In Interface Builder add a zero size subview and use the Editor->Arrange->Send to Back menu command.
If you're not using Interface Builder, but instead are subclassing the UIWebView, then it can be done by creating a UIView instance variable called scrollFixView and overriding the following methods:
- (void)didMoveToSuperview
{
[super didMoveToSuperview];
if ([self superview].subviews.firstObject == self) {
_scrollFixView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
_scrollFixView.hidden = YES;
[[self superview] insertSubview:_scrollFixView belowSubview:self];
}
}
- (void)removeFromSuperview
{
if (_scrollFixView) {
[_scrollFixView removeFromSuperview];
_scrollFixView = nil;
}
[super removeFromSuperview];
}
I had the same problem so I tried a few things:-)
This worked for me, but correct me please if there is a better way.
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
if(self.navigationController.navigationBar.translucent == YES)
{
_webView.scrollView.contentOffset = CGPointMake(_webView.frame.origin.x, _webView.frame.origin.y - 54);
}
}
So basically you need to :
1) Add the UIWebView delegate method - webViewDidFinishLoad:
2) Then I setup an if statement to check if the translucent option is active.
The last one you only need to do of course if you give the user the option within your app.
The number after the _webView.frame.origin.y is just for my app. It may differ for you.
I solved this problem by simply setting a constraint on the WebView, setting the top space between it and the View top to 0, causing the NavBar to overlap the whitespace.
One alternative to Jeff Kranenburg's method is to subclass and override the UIWebView subclasses' UIScrollViewDelegate method scrollViewDidScroll:. This is only appropriate if scrolling is turned off for your subclass.
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if ([[self superclass] instancesRespondToSelector:_cmd]) {
[super scrollViewDidScroll:scrollView];
}
[self fixUpScrollViewContentOffset];
}
- (void)fixUpScrollViewContentOffset
{
if (!CGPointEqualToPoint(self.scrollView.contentOffset, CGPointZero)) {
self.scrollView.contentOffset = CGPointZero;
}
}
I already got it .
here my logic code, When the application open the website you must get the size of your webview then set it on height
here my code
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) webpage.getLayoutParams();
p.height = webpage.getHeight();
// check if how long you need to set your height for webpage then set it :)
Log.e(" webpage.getHeight()", String.valueOf(webpage.getHeight()));
webpage.setLayoutParams(p);
Hope you will take my code and my answer to :) works on any devices even tabs too :)

Mac App WebView background

How is it possible to set the an image as background of the WebView in a Mac App? Because the WebView has that "bouncing" effect, if you scroll further down than the content, the background is usually just white. Is it possible to set a Background-image like it is possible for the UIWebView?
EDIT: The alternate way would be to completely deactivate the bouncing-effect of the webView.
If you are creating this webview programically then create an image then create the webview. Make sure their positions (x,y) and sizes (height, width) are the same.
If you are doing this through IB put down an image (litterally just drag an image) then put the webview on top of it.
Here is a way I found that stops the bouncing:
id sub = self.web.subviews[0];
if ([sub isKindOfClass:[WebFrameView class]])
[sub setAllowsScrolling:NO];
The class check may not be needed, but I like to make sure.
We can add background image in WebView using cocoa. to do this we need to add css for body tag.
Create a webview:
WebView *webView;
Fetch image form bundle path:
NSString *path = [[NSBundle mainBundle] pathForResource:#"my-bg" ofType:#"jpg"];
write Css for body tag.
NSMutableString *htmlBuilder = [[NSMutableString alloc] init];
[htmlBuilder appendString:#"body {"];
[htmlBuilder appendString:[NSString stringWithFormat:#" background-image: url('file://%#');",path]];
[htmlBuilder appendString:#"}"];
Load this image on webview
[[webView mainFrame] loadHTMLString:htmlBuilder baseURL:nil];
[webView setDrawsBackground:NO];
Your image will be added in background on webview.

Setting NSBox's setContentView with NSImageView not working

I have an NSBox set up in my main view that accepts drag and drop. We store the URL into str. We then load the image and add it to the content view of NSBox.
imageView = [[NSImageView alloc] initWithFrame:CGRectMake(0, 0, 390, 150)];
NSURL *imageURL = [NSURL URLWithString:str];
NSImage *image = [[NSImage alloc] initByReferencingURL:imageURL];
[imageView setImage:image];
[self setContentView:imageView];
However, this doesn't do anything. The image is not displayed in the nsbox.
Another oddity. At first I was trying to add the NSImageView via interface builder, but the only image container they had was IKImageView... Is this odd? Isn't NSImageView more ubiquitous? I mainly develop on iOS, so I have the version from the ios developer site.
Any thoughts?
Edit: I should also add, when I was using IKImageView in IB, the image would show up.
Edit2: I've also tried just taking the initWithFrame out and replacing it with just init, no go.
The problem was that I was using initByReferencingURL to get the NSImage. This doesn't work for local files, so instead I used initByReferencingFile and everything worked out well!

To Convert HTML doc to image in cocoa

is it possible to convert the HTML page to image in cocoa?
Actually i have created the complete view in the HTML and now i want to convert the whole html preview to the image (any jpeg or png etc.).
I couldn't find any resource or sample on the web, which provides some sort of help on my above queries.It's highly appreciated if someone could share his wisdom on how I can achieve this.
Thanks in advance..
First off, I'd like to thank sergio... his answer got me started but I thought I'd share some of the code that I didn't find obvious that I had to write to make it work:
Here's how to make a thumbnail for a page without ever having it displayed:
// Your width and height can be whatever you like, but if you want this to render
// off screen, you need an x and y bigger than the superview's width and height
UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(largerScreenDimension, largerScreenDimension, largerScreenDimension, largerScreenDimension)];
[self.view addSubview:webView]; // UIWebViews without an assigned superview don't load ever.
webView.delegate = self; // or whoever you have implement UIWebViewDelegate
webView.scalesToFit = YES; // This zooms the page appropriately to fill the entire thumbnail.
[webView loadRequest:[NSURLRequest requestWithURL:url]];
Then implement this in your delegate:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
UIGraphicsBeginImageContext(webView.bounds.size);
[webView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *webViewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *thumbnailData = UIImagePNGRepresentation(webViewImage);
[webView removeFromSuperview];
}
Finally, to display this thumbnail you'll need something like:
thumbnailImageView.image = [UIImage imageWithData:thumbnailData];
As a bonus thing I'll mention, I wanted multiple thumbnails to be generated at once. I found using objc_setAssociatedObject() and objc_getAssociatedObject() to be very helpful with keeping track of which webView was loading which thumbnail. Going into detail on how that worked is beyond the scope of this question, though.
You can draw your view in an image context, like this:
UIWebView* view = ...
....
UIGraphicsBeginImageContext(view.bounds.size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imagedata = UIImagePNGRepresentation(viewimage);
NSString *encodedString = [imageData base64Encoding];
Another option would be using Quartz PDF engine to create a PDF.