How to set scale in WKWebview? - javascript

I´m trying to modify the scale of a page load in a WKWebView. It is working as far as I´m looking in the html. But the actual scale in the WKWebview doesn´t change.
Here´s how I inject the script:
let script =
"var viewport = document.querySelector(\"meta[name=viewport]\");" +
"viewport.setAttribute('content', 'width=device-width, initial-scale=0.4, user-scalable=0');" +
let userScript = WKUserScript(source: script,
injectionTime: WKUserScriptInjectionTime.atDocumentEnd,
forMainFrameOnly: true)
userContentController.addUserScript(userScript)
Print the html:
webView.evaluateJavaScript("document.getElementsByTagName('html')[0].innerHTML", completionHandler: { (innerHTML, error) in
print(innerHTML)
})
HTML result in console:
Optional(<!--<![endif]--><head>
<title>Bitcoin (BTC) $2391.84 (1.85%) | CoinMarketCap</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=0.4, user-scalable=0">
<meta name="google-site-verification" content="EDc1reqlQ-zAgeRrrgAxRXNK-Zs9JgpE9a0wdaoSO9A">
<meta property="og:type" content="website">
I´m asking myself if this is the right approach. I also tried: let script = document.body.style.zoom = '0.8'; and let script = document.body.style.webkitTransform = 'scale(0.8)'; which is both working in terms of scale, but using this method, the timeperiod slider in this highchart loses its functionality. Any kind of new ideas would be much appreciated.

Add <meta name="viewport" content="width=device-width, shrink-to-fit=YES"> to your HTML file.
(I added right after but not sure if you can add it anywhere)
In my case I have html files for privacy in my Xcode project. I added that javascript code right below the and it did the trick for me.
It works as if you used scalePageToFit in UIWebView.
Hope it helps.

Related

Having issues using js to randomly reassign a css variable

I'm working on a part of a page that should load a random image from a folder every fraction of a second for a rapid shuffle. I've gotten it to get the file name and randomly set a style for it. Problem is, not at all how I was intending to do so. I want to set the css variable "--background-images" in my stylesheet, however all it seems to be doing upon manually running the function in console is adjust the html doc like so:
<html lang="en" style="--background-images\::url(\.\.\/\.\.\/rsrc\/acct-crt-page-images\/acct-crt-street-mural-16\.png);"><head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Account - Page 37</title>
<script src="../scripts/script.js"></script>
<link rel="stylesheet" href="../styles/account-creation-style.css" type="text/css">
</head>
Obviously this isn't what I was aiming to change--and beyond that I have no idea what that url it inserted is as it looks like a nightmare. I'm aiming to replace only the line in the css file. This is my js code:
// Load the root CSS variables
const style_root = document.querySelector(':root')
function random_image() {
// Get a random index postion of the images array
array_index = Math.floor(Math.random() * 19)++;
// Change the --background-images css variable based on the random index
style_root.style.setProperty(`--background-images`, `url(../../rsrc/acct-crt-page-images/acct-crt-street-mural-${array_index}.png)`);
}
I don't really know where to start or what is happening here now--I've been working with this aspect of the website for almost a week, and I was getting close but this roadblock has had me for 2-3 days.
I'm attempting to change a line of css, but instead I've gotten a weird and confusing line that doesn't function in html.

Scraping a messy javascript-heavy website with python

I was trying to scrape the household links from this page :
https://www.sreality.cz/en/search/to-rent/apartments?page=2
For instance, for the first apartment I would like to obtain the link with:
https://www.sreality.cz/en/detail/lease/flat/1+kt/plzen-jizni-predmesti-technicka/25873756#img=0&fullscreen=false
However the website is quite heavy on javascript. By using requests.get() I only obtain an uninformative chunk of html code:
from requests import get
i = 2
url = f"https://www.sreality.cz/en/search/to-rent/apartments?page={i}"
response = get(url)
print(response.text)
-----------------------------
<!doctype html>
<html lang="{{ html.lang }}" ng-app="sreality" ng-controller="MainCtrl">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1.0,minimal-ui">
<!--- Nastaveni meta pres JS a ne pres Angular, aby byla nastavena default hodnota pro agenty co nezvladaji PhantomJS --->
<title ng:bind-template="{{metaSeo.title}}">Sreality.cz ⢠reality a nemovitosti z celé ÄR</title>
<meta name="description" content="NejvÄtší nabídka nemovitostí v ÄR. Nabízíme byty, domy, novostavby, nebytové prostory, pozemky a další reality k prodeji i pronájmu. Sreality.cz">
<meta property="og:title" content="Sreality.cz ⢠reality a nemovitosti z celé ÄR">
<meta property="og:type" content="website">
<meta property="og:image" content="https://www.sreality.cz/img/sreality-logo-og.png">
-----------------------------
ETC ...
The question is therefore, how to proceed with some simple scraping activity for websites of this kind ?
Thanks in advance for the help.
I don't think that website has a public API but looking at the API calls from the network tab I could fetch the details for your need and make it as link have a look at the below code.
Let me know if you have any questions :)
import time
import requests
page=2
numberofresults=20
epochmiliseconds=round(time.time() * 1000)
paramsdict={
"category_main_cb":1,
"category_type_cb":2,
"page":page,
"per_page":numberofresults,
"tms":epochmiliseconds
}
data=requests.get("https://www.sreality.cz/api/en/v2/estates",params=paramsdict).json()
for lead in data["_embedded"]["estates"]:
locality=lead["seo"]["locality"]
name=lead["name"]
hash_id=lead["hash_id"]
typedata=[s for s in name.split(" ") if "+" in s][0].replace("\u00a0"," ").split(" ")[0]
print(f'https://www.sreality.cz/en/detail/lease/flat/{typedata}/{locality}/{hash_id}'))
Output:
First ask website, if they provide any API to get the desired information.
To deal with javascript during the scraping only request will not work. You should go Selenium only or for scrapy in combination of scrapy-selenium. These two allow loading of javascript during scraping.
Feel free to ask if you have any other question.

How prevent zoom in mobile using javascript?

To prevent zoom in html you can use <meta name="viewport" content="user-scalable=0"/> in the header.
How about implement prevent zoom with javascript?
The same way.
Native:
var tag = document.createElement('meta');
tag.name="viewport";
tag.content = "user-scalable=0";
document.head.appendChild(tag);
jQuery:
$('<meta name="viewport" content="user-scalable=0"/>').appendTo('head');

Turn off Zurb Foundation 5 meta tags

Searched all over the internet but could not find anything about it.
How can I turn off this zurb foundation 5 meta tags in <head>:
<meta class="foundation-mq-small">
<meta class="foundation-mq-small-only">
<meta class="foundation-mq-medium">
<meta class="foundation-mq-medium-only">
<meta class="foundation-mq-large">
<meta class="foundation-mq-large-only">
<meta class="foundation-mq-xlarge">
<meta class="foundation-mq-xlarge-only">
<meta class="foundation-mq-xxlarge">
<meta class="foundation-data-attribute-namespace">
1) You shouldn't. They are needed for some Foundation's JS plugins.
2) If you want to just use Reveal Modal, you don't need removing these meta tags. You can simply include only this plugin into your webstie:
<script src="/js/foundation.js"></script>
<script src="/js/foundation.reveal.js"></script>
Or, if you are using foundation.min.js, you can init only this plugin:
$(document).foundation('reveal');
3) If you are absolutely confident you want to remove these tags for some reason, you have three possibilities:
Editation of file foundation.js
Remove this part from the file foundation.js.
header_helpers([
'foundation-mq-small',
'foundation-mq-small-only',
'foundation-mq-medium',
'foundation-mq-medium-only',
'foundation-mq-large',
'foundation-mq-large-only',
'foundation-mq-xlarge',
'foundation-mq-xlarge-only',
'foundation-mq-xxlarge',
'foundation-data-attribute-namespace']);
Removal by plain JavaScript (after include)
Include thit code snippet somwhere into your website. It should be run after Foundation initialization.
var metas = document.getElementsByTagName('meta');
for (index = metas.length - 1; index >= 0; index--) {
var metaClass = metas[index].getAttribute('class') || '';
if (metaClass.indexOf('foundation') > -1) {
metas[index].parentNode.removeChild(metas[index]);
}
}
Removal by jQuery (after include)
This code snippet needs jQuery, however, you should have it included already because Foundation depends on it. And, of course, it should be also run after Foundation initialization.
$('meta[class*=\'foundation\']').remove();

How to add meta tag in JavaScript

I want to add <meta http-equiv="X-UA-Compatible" content="IE=edge"> for a particular page.
But my pages are rendered inside one HTML tag. Only the content is changing on clicking different templates. So i cannot add the <meta> in <HEAD> section.
Is there any way to add the <meta http-equiv="X-UA-Compatible" content="IE=edge"> using javascript ?
You can add it:
var meta = document.createElement('meta');
meta.httpEquiv = "X-UA-Compatible";
meta.content = "IE=edge";
document.getElementsByTagName('head')[0].appendChild(meta);
...but I wouldn't be surprised if by the time that ran, the browser had already made its decisions about how to render the page.
The real answer here has to be to output the correct tag from the server in the first place. (Sadly, you can't just not have the tag if you need to support IE. :-| )
$('head').append('<meta http-equiv="X-UA-Compatible" content="IE=Edge" />');
or
var meta = document.createElement('meta');
meta.httpEquiv = "X-UA-Compatible";
meta.content = "IE=edge";
document.getElementsByTagName('head')[0].appendChild(meta);
Though I'm not certain it will have an affect as it will be generated after the page is loaded
If you want to add meta data tags for page description, use the
SETTINGS of your DNN page to add Description and Keywords. Beyond
that, the best way to go when modifying the HEAD is to dynamically
inject your code into the HEAD via a third party module.
Found at http://www.dotnetnuke.com/Resources/Forums/forumid/7/threadid/298385/scope/posts.aspx
This may allow other meta tags, if you're lucky
Additional HEAD tags can be placed into Page Settings > Advanced
Settings > Page Header Tags.
Found at http://www.dotnetnuke.com/Resources/Forums/forumid/-1/postid/223250/scope/posts.aspx
Like this ?
<script>
var meta = document.createElement('meta');
meta.setAttribute('http-equiv', 'X-UA-Compatible');
meta.setAttribute('content', 'IE=Edge');
document.getElementsByTagName('head')[0].appendChild(meta);
</script>
As specified by #marcellothearcane, for modern browser, you can also use:
var meta = document.createElement('meta');
meta.httpEquiv = "X-UA-Compatible";
meta.content = "IE=edge";
document.head.appendChild(meta);
Supported browser here: document.head
Try
document.head.innerHTML += '<meta http-equiv="X-UA-..." content="IE=edge">'

Categories